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

通过Javascript定位Django模型中的动态内容,javascript,django,Javascript,Django,我试图制作一个个人博客模板,但我被困在一个显示所有文章预览的页面上。在此页面中,有两列,#内容列左侧和#内容列右侧,预览应根据列的高度放置在其中一列上(较短的列接收下一次发布预览)。我一直在尝试通过JavaScript实现,使用一个包含“虚拟”数据的数组: 函数processPosts(){ var cleft=document.getElementById('content-column-left'); var cright=document.getElementById('content-c

我试图制作一个个人博客模板,但我被困在一个显示所有文章预览的页面上。在此页面中,有两列,
#内容列左侧
#内容列右侧
,预览应根据列的高度放置在其中一列上(较短的列接收下一次发布预览)。我一直在尝试通过JavaScript实现,使用一个包含“虚拟”数据的数组:

函数processPosts(){
var cleft=document.getElementById('content-column-left');
var cright=document.getElementById('content-column-right');
对于(var i=0;i

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

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

例如,Django模板输出如下:

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

帖子已被订购,并且已经来自服务器。问题是,我需要(或者至少我认为我需要)使用javascript来正确显示它们,而我似乎无法从javascript中正确操作django变量。@Daniel:javascript不需要修改服务器端变量;它可以在客户端重新排列元素。也许我会修改我的答案来澄清一点。我对你答案的回答也不清楚,对不起。通过操纵变量,我的意思是我甚至不能得到它们的值@Valbrand:我的建议是,在服务器端,您将其输出为只有一列,然后让JavaScript将一列重新排列为两列。我已经在我的答案中添加了一些可能会有所帮助的具体代码。非常感谢你的答案,现在我明白你的意思了。把我从很多麻烦中解救出来!首先,我尝试只将一个post列表传递给模板(类似于posts.objects.all()),然后从javascript使用它,但没有成功。我也尝试将其作为json传递给模板。
<div id="posts">
    <div class="post">...</div>
    <div class="post">...</div>
    <div class="post">...</div>
    <div class="post">...</div>
</div>
// 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.)
}