简体   繁体   中英

Django template parsing order

Is the parsing order for Django templates specified somewhere in the Django documentation?

Based on the documentation for writing custom template tags and the API, it seems Django uses a depth-first traversal for building the node tree. However, I can't find any statement in the Django documentation that guarantees this. In particular, I'd like to know if the node tree is completely assembled before any rendering is done.

Also, how does this affect template inheritance? Are the {% block ... %} tags in the derived template parsed at their location in the base template or are they parsed by the {% extends "..." %} tag before the base template?

The answer is yes, all nodes are created when you create a Template object. But the magic happens when you call the render method of this object. This Template object has a NodeList with it that is rendered within a context. This rendering is done as you said before, depth first, and it just gets the inners child strings (html) appended to the father Node. Here is the NodeList class where the node rendering is done. So, the root node is the one to get all the nodes appended to it to finally generate the file. And if you remember, the extends template tag must be first in the template so it becomes the root node who get all the already rendered nodes in it.

Now, what about inheritance? How is the exteds root node rendered? Well, I haven't figured out all about the context role here, but there is a ExtendsNode that is created by the extends template tag. This type of node recieves the parent template name (your base template) and a context with all the variables, blocks and nodes of the child template (the one you actually call to render). So when this node is rendered, it does the same thing that every node does, append his child nodes. The main difference in this class is that it gets the nodes marked with the block template tag from the child's template context, and appends it everywhere you defined a block template tag with that name in the parent template.

So the nodes are created first, and the extends template tag manage to get them when you render the template.

If you want to know how nodes a created, you can look for the Token and Parser class at the Django code.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM