python - How to parse Django templates for template tags -
situation
i'm writing checker program checks django templates. example want check if django templates use url
template tag, use quotes on first parameter django 1.5 compatible. want check have included {% load url future %}
in templates.
for example if program parses following django template, want raise exception.
{% extends 'base.html' %} <td> <a href="{% url first second %}"> </a> </td>
but template should parsed without exception.
{% extends 'base.html' %} {% load url future %} <td> <a href="{% url 'first' second %}"> </a> </td>
i'm not limited simple example. have other parsings do. example want check how many load
template tags present in template.
question
how can elegantly solve parsing problem?
- i don't want use regular expressions.
- i django self has utilities in regard. think using them idea, don't know how.
- i want run program separately django. don't want django run program (with
render_to_response
). (this important)
code
please show me code can solve example mentioned. want detect whether {% load url future %}
in code. want check every url
template tag , check if first argument quoted.
bonus:
- i want able see rendered html django generates template, , html parsing on it. (for example pyquery)
you can use compile_string
method.
>>> django.template.base import * >>> settings.configure() >>> compile_string("<a href='ab'></a>{% cycle 'row1' 'row2' rowcolors %}", none) >>> [<text node: '<a href='ab'></a>'>, <django.template.defaulttags.cyclenode object @ 0x10511b210>]
the compile string method utilized template
class , method used produce node list. tested in django 1.8 alpha.
Comments
Post a Comment