用django渲染模板内的函数是不可能的?

时间:2015-03-21 18:52:46

标签: django python-3.x django-models django-templates

我想渲染一些在模型函数中生成的文本,如:

def get_introduction(self):
    # Find first paragraph
    all_paragraph = self.text.split("</p>")
    # Delete p tag
    paragraph_content = all_paragraph[0].replace("<p>", "")
    return paragraph_content

def get_text_content(self):
    # Find first paragraph
    introduction = self.get_introduction()
    post_content = self.text.replace("<p>%s</p>" % introduction, "")
    return post_content

我希望在模板中呈现get_text_content函数的结果:

<div class="post-content">
    <p>{{ post.get_introduction }}</p>
    {% if post.image %}
    <img src="{{  post.get_absolute_image_url }}" />
    {% endif %}
    {{ post.get_text_content | safe }}
</div>

但只有介绍和图像在此模板中呈现。为什么?

1 个答案:

答案 0 :(得分:0)

刚刚发现了这个问题。

这不是一个很好的方式,但至少它有效。

我改变了get_text_content的代码:

def get_text_content(self):
        # Find first paragraph
        introduction = self.get_introduction()
        introduction_with_tag = "<p>%s</p>" % introduction
        post_content = self.text[len(introduction_with_tag):]
        return post_content