marxin
marxin

Reputation: 3922

Django template system - getting fields from template

Is there a function that returns a list of fields that are expected in template? For example, I have the following template:

hello i am {{ name }}. {% for i in docs %} i have doc {{ i }}

Written in file. And i want to get a dict which contains:

{'name': 'str', 'docs': 'list'}

Is there something like that or i have to write it by myself?

Upvotes: 0

Views: 89

Answers (2)

jdg
jdg

Reputation: 2298

The builtin {% debug %} tag may be helpful for you, however I don't know if I fully understand what you are asking. Basically, if you put the debug tag in your template it will print a lot of useful stuff, including all the variables available in your template.

Perhaps you could take a look at the source code for the debug tag (because they have access to all the variables there), and build a custom tag tag based off of this. Taking a glance at the source, this seems like it would be really simple to do.

Upvotes: 0

Mp0int
Mp0int

Reputation: 18727

As far as i know, NO....

Your template contains some html and some place holders (and may be something else). What render_to_template doing is, it gets a context dictionary which contain some keys and some data attached to that keys and a template. Then it places the values to those place holders according to their key names, execute some loops or condition checks if your template contains control flows like {% if...%} or {%for....%}

If TEMPLATE_DEBUG is closed in your settings, and if there is a place holder with no matching key in your context dictionary, then it will skip that without raising any error.

Also, if you pass a form object to your template and place your object directly to template as it is (without calling each field separately) [ex: {{form}} or {{form.as_p}} then django will check for fields on the form and palce them as it is shown here. In a such situation, you will only know that form is used. You have to check which fields are used from your Form definition.

If you look through that process, you must know what you need to place your context dictionary. You may write a parser to parse your template but it is far more difficult than just examining the template and find missing data, i guess.

Upvotes: 2

Related Questions