Paulo
Paulo

Reputation: 7342

How to parse a django template and render specific tag

Is it possible to parse a django template and only render a specific tag ? This snippet is close to what I'm looking for but it doesn't return the entire template. Basically if I have this template as input

<html>
<title>{% block title%}{% endblock %}</title>
<body>
{% block content %}
{% mycustomtag "args" %}
{% endblock content %}
</body>
</html>

and i want to only render mycustomtag this is the output Im looking for

<html>
<title>{% block title%}{% endblock %}</title>
<body>
{% block content %}
<p>Result from mycustomtag</p>
{% endblock content %}
</body>
</html>

Thanks.

Upvotes: 2

Views: 1443

Answers (1)

Tisho
Tisho

Reputation: 8482

If I properly understand your question, then there is a way to do that, using the {% verbatim %} tag. It will be added in Django 1.5, but for now you can use it as your custom tag - here is the source: https://code.djangoproject.com/ticket/16318

The only drawback here is that you cannot use directly this template, it needs double rendering. If this is what you need - then everything is OK.

To use it, all you need to do is to enclose the other tags with {% verbatim %} :

{% load my_custom_tags %}  <-- this is needed to load the 'verbatim' and 'mycustomtag' tags
{% verbatim %}
<html>
<title>{% block title%}{% endblock %}</title>
<body>
{% block content %}
{% endverbatim %}

{% mycustomtag "args" %}

{% verbatim %}
{% endblock content %}
</body>
</html>
{% endverbatim %}

I've made a simple test with this template:

@register.simple_tag
def mycustomtag(a):
    return "<p>%s</p>" % a

....

from django.template import loader, Context
print loader.get_template("test.html").render(Context({}))

This prints the following:

<html>
<title>{%block title%}{%endblock%}</title>
<body>
{%block content%}

<p>args</p>

{%endblock content%}
</body>
</html>

Hope this could be helpful.

Upvotes: 3

Related Questions