开发者

django custom tags with template blocks?

I just started learning about custom tags in django and was wondering if there was a feature that allowed the injection of data as if they were blocks/tags.

The real problem is this, tags work great, b开发者_如何学Gout lets say my tag is some html and javascript, does that mean I have to call two tag functions and inject them into the page that way. It almost seems like the solution is to use a template where you fill in the blocks and it appends the data that way, but that can't do what the custom tags need to do. So how would you solve a problem like this?


You need to use django inclusion tags

Infact, django admin itself uses these tags for very similar purpose.

From the documentation, Define a function like this, which is aware of the template it needs to render from

@register.inclusion_tag('results.html')
def show_results(poll):
    choices = poll.choice_set.all()
    return {'choices': choices}

And the template:

<ul>
{% for choice in choices %}
    <li> {{ choice }} </li>
{% endfor %}
</ul>

Then you insert a tag as follows:

{% show_results poll %}

Which will provide:

<ul>
   <li>First choice</li>
   <li>Second choice</li>
   <li>Third choice</li>
</ul>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜