Tutorial :django custom tags with template blocks?



Question:

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, but 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?


Solution:1

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>  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »