开发者

Django template parsing order

开发者 https://www.devze.com 2023-02-13 07:16 出处:网络
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

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 templa开发者_StackOverflow中文版te 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消