2013-07-20 16 views
1

我試圖製作一個個人博客模板,並且我被困在顯示所有帖子預覽的頁面。在此頁面中,有兩列#content-column-left#content-column-right,預覽應放置在基於列高度的列之一(較短的列接收下一篇文章預覽)。我一直試圖通過JavaScript來實現,其中包含「虛擬」數據的數組:通過Javascript定位來自Django模型的動態內容

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。

+0

首先,我試着只傳遞一個帖子列表到模板(類似Posts.objects.all()),然後從JavaScript使用它,無濟於事。我試圖將它作爲json傳遞給模板。 – Valbrand

回答

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.) 
} 
+0

帖子已經訂購併且已經從服務器發出。問題是,我需要(或者至少我覺得我需要)使用javascript來正確顯示它們,而且我似乎無法正確處理來自javascript的django變量。 – Valbrand

+0

@Daniel:JavaScript不需要修改服務器端變量;它可以重新排列客戶端的元素。也許我會編輯我的答案來澄清一點。 – icktoofay

+0

我的答覆也不清楚,對不起。通過操縱變量,我的意思是我無法獲得他們的價值! – Valbrand