如何影响Django for循环中的各个条目?

问题描述

我在Django中创建了一个for循环,其中显示用户上传文章。如果是长篇文章,我将截断文本的最大长度为150个字符,但想让读者选择通过单击“阅读更多”来使用jquery函数扩展文本。 这是我的模板:

{% for post in posts %}
    {% if post.content|length > 150 %}
        <p class="half-content">{{ post.content|truncatechars:150 }}<a href="javascript:void();" class="show-hide-btn">read more</a></p>
        <p class="full-content" style="display: none;">{{ post.content }}</p>
    {% else %}
        <p>{{ post.content }}</p>
    {% endif %}
{% endfor %}

这是我的jquery函数

$(document).ready(function(){
    $(".show-hide-btn").click(function(){
        $(".half-content").hide();
    });
});
$(document).ready(function(){
    $(".show-hide-btn").click(function(){
        $(".full-content").show();
    });
});

它可以按我的意愿运行,除了“阅读更多”链接可扩展页面上的所有文章,而不仅仅是带有适当主键的文章。我知道我需要在代码中的某个地方包含{{post.id}},但到目前为止,我尝试过的所有方法均无效。

解决方法

尝试一下

{% for post in posts %}
    {% if post.content|length > 150 %}
        <p class="half-content" id="half-{{post.id}}">{{ post.content|truncatechars:150 }}<a data-id="{{post.id}}" href="javascript:void();" class="show-hide-btn">read more</a></p>
        <p class="full-content" id="full-{{post.id}}" style="display: none;">{{ post.content }}</p></div>
    {% else %}
        <p>{{ post.content }}</p>
    {% endif %}
{% endfor %}


<script>
    $(document).ready(function(){
        $(".show-hide-btn").click(function(){
            var id = $(this).data("id");
            $("#half-"+id).hide();
            $("#full-"+id).show();
        });
    });
</script>