1

個人のブログ テンプレートを作成しようとしているのですが、すべての投稿のプレビューを表示するページで行き詰っています。このページには、 と の 2 つの列が#content-column-leftあり#content-column-right、プレビューは、列の高さに基づいて列の 1 つに配置する必要があります (短い方の列が次のポスト プレビューを受け取ります)。「ダミー」データを含む配列を使用して、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を使っています。

4

1 に答える 1

0

サーバー側では、すべての投稿を 2 つの列にまとめようとせずに順番に並べます。次に、クライアント側で、投稿を 2 つの列にレイアウトすることを 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.)
}
于 2013-07-21T04:09:42.723 に答える