Rendering custom template tags from database in Django

瘦欲@ 提交于 2019-12-04 19:34:50

It turns out that the render_as_template tag found here DOES work, I just misunderstood it. Beginner's mistake. There are two things that were not specified in the documentation for the snippet that I failed to pick up on my own.

So, you put the render_as_template tag in your template like this:

{% load render_as_template %}
{% render_as_template myobject.attribute %}

Thus allowing any template tags within myobject.attribute to be rendered. Here is where I ran into trouble:

First, I was passing my post body to render_as_template as selected_post.body|truncatewords_html:"100"|safe or as selected_post.body|safe. The template tag is unable to process the filters on the attribute and seems to interpret them as part of the object's name. Since this object does not exist, nothing is rendered. What I need in my template is:

{% autoescape off %}
{% filter truncatewords_html:"100" %}
{% render_as_template selected_post.body %}
{% endfilter %}
{% endautoescape %}

Second, if the content of my post is:

My first paragraph.
{% my_custom_tag var1 var2 %}
My second paragraph.

Then in order for my_custom_tag to be interpreted, I need to add to my post:

{% load my_custom_tag %}

Now it works perfectly!

To create custom tags in Django, you need to write a tag function then register it. Link to Official Django Docs on the subject.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!