如何影响 django for 循环中的单个条目? [英] How can I affect individual entries in a django for loop?
问题描述
我在 Django 中创建了一个 for 循环,用于显示用户上传的文章.对于长文章,我会将文本截断为最大长度为 150 个字符,但希望让读者可以选择使用 jquery 函数扩展文本,方法是单击阅读更多".这是我的模板:
I have created a for loop in Django which displays articles uploaded by users. In the case of long articles I will truncate the text to a max length of 150 chars, but want to give readers the option of expanding the text using a jquery function, by clicking 'read more'. This is my template:
{% 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 函数:
And here is my jquery function:
$(document).ready(function(){
$(".show-hide-btn").click(function(){
$(".half-content").hide();
});
});
$(document).ready(function(){
$(".show-hide-btn").click(function(){
$(".full-content").show();
});
});
它按我的意愿工作,除了阅读更多"链接扩展页面上的所有文章,而不仅仅是具有适当主键的文章.我知道我需要在代码中的某处包含 {{ post.id }},但到目前为止我尝试过的所有方法都无效.
It works how I would like it to, except that the 'read more' link is expanding all the articles on the page, not just the one with the appropriate primary key. I know I need to include {{ post.id }} in my code somewhere, but so far everything I have tried has been ineffective.
推荐答案
试试这个,
{% 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>
这篇关于如何影响 django for 循环中的单个条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!