通过Javascript定位Django模型的动态内容

时间:2013-07-20 22:58:07

标签: javascript django

我正在尝试创建一个个人博客模板,而我却停留在显示所有帖子预览的页面上。在此页面中,有两列#content-column-left#content-column-right,预览应根据列的高度放置在其中一列上(较短的列接收下一个帖子预览)。我一直试图通过JavaScript来做,包含一个包含“虚拟”数据的数组:

function processPosts() {
    var cleft = document.getElementById('content-column-left');
    var cright = document.getElementById('content-column-right');

    for (var i = 0; i < testeVector.length; i++) {
        var preview = document.createElement('div');
        preview.className = 'post-preview';
        var conteudo = postsVector[i];
        var aux = document.createElement('h1');
        aux.appendChild(document.createTextNode(content.title))
        preview.appendChild(aux);
        preview.appendChild(document.createTextNode(content.content));

        if(cleft.clientHeight > cright.clientHeight) {
            cright.appendChild(preview);
        } else {
            cleft.appendChild(preview);
        }
    };
}

上面的代码按预期工作。问题是,帖子保存在博客的数据库中,我不知道如何从数据库中检索它们,所以我可以在Javascript上使用帖子的数据。一直在寻找一种方法(没有结果)在视图代码上创建待显示帖子的列表,并在JavaScript上使用这样的列表。顺便说一下,我正在使用Django。

1 个答案:

答案 0 :(得分:0)

在服务器端,我将所有帖子按顺序排列,而不是试图将它们放在两列中。然后在客户端,您可以使用JavaScript处理将帖子分成两列。

例如,你有Django模板输出如下:

<div id="posts">
    <div class="post">...</div>
    <div class="post">...</div>
    <div class="post">...</div>
    <div class="post">...</div>
</div>

在JavaScript中,在页面加载时,您可以从#posts中取出所有帖子并创建列并根据需要将帖子排列到列中:

// First, retrieve our element containing all the posts:
var posts = document.getElementById('posts');

// Then, create the columns we want to put the posts into:
var leftColumn = document.createElement('div');
var rightColumn = document.createElement('div');
// You'll probably want to give them IDs or classes so you can style them.

// Next, we'll replace the #posts div with the two columns:
posts.parentNode.insertBefore(leftColumn, posts);
posts.parentNode.insertBefore(rightColumn, posts);
posts.parentNode.removeChild(posts);

// Now we have two empty columns on the page and the original #posts div stored
// within the posts variable.  We can now take elements out of the #posts div and
// place them into the columns.

while(posts.hasChildNodes()) {
    // Fetch the next element from the #posts div and remove it.
    var post = posts.firstChild;
    posts.removeChild(post);
    // We might catch some whitespace here; if so, discard it and move on.
    if(post.nodeType === Node.ELEMENT_NODE) {
        continue;
    }
    // Put the post in one of the columns, based on your logic.
    // (I think you can figure this out, based on the code in your question.)
}