我想使用Django模板标记过滤器截断我的帖子内容,例如(| truncatewords_html:my_number)。但是使用省略号的href链接将用户重定向到详细的帖子完整内容。
除了定义自定义模板标记过滤器(在类似但相当旧的线程中引用)之外,我想知道是否有内置方法来实现所需的结果。
答案 0 :(得分:0)
我解决了这个问题。我没有在Django的模板标签过滤器中构建逻辑,而是发送我的JSON API数据(使用Django Rest Framework构建)供我的前端使用(我使用的是JQuery库)。代码如下:
Serializers.py:
class PostListSerializer(ModelSerializer):
url = post_detail_url
username = serializers.SerializerMethodField()
date_created = serializers.SerializerMethodField()
def get_username(self, obj):
return obj.user.username
def get_date_created(self, obj):
return obj.created.strftime('%b %d %Y | at %I:%M %p')
class Meta:
model = Post
fields = [
'id',
'username',
'title',
'slug',
'content',
'url',
'date_created',
]
views.py:
class PostListAPIView(generics.ListAPIView):
queryset = Post.objects.all()
serializer_class = serializers.PostListSerializer
最后是我的post_list.html:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: '/api/posts/',
method: 'GET',
success: function(data){
// iterate through the array of objects
$.each(data, function(key, value){
var postUser= value.username;
var postTitle = value.title;
var postSlug = value.slug;
var postCreated = value.date_created;
var postContent = value.content;
var postShort;
if (postContent.length >= 50){
// truncate long posts
postShort = jQuery.trim(postContent).substring(0, 50).split(" ").slice(0, -1).join(" ")
+ "<a href='/posts/" + postSlug + "'>" + "..." + "</a>";
} else {
postShort = postContent;
}
$('#posts-container').append(
"<div>" + "<h4>" + postUser + ": " + "<a href='/posts/"
+ postSlug + "'>" + postTitle + "</a>" + "<h5>"
+ postCreated + "</h5>" + postShort + "</div>" + "<hr>"
);
});
},
error: function(data){
console.log('error');
console.log(data);
}
});
});
</script>