Django
1
Django templates
作者: n5321
In practice, Django’s templates are simply HTML files, with some special syntax and tools that let Django render the HTML page on-the-fly for the visiting User from the Views. The templates use a templating language that allows developers to insert dynamic data into the HTML page, such as variables, loops, and conditional statements. Let’s deep dive and discuss some ways of efficiently working with Django templates.
*include *the {% include %} tag allows one to include another template within another template.
*extends *The {% extends %} tag commands Django to inherit from another template and override specific content blocks.
*load *The {% load %} tag allows developers to load custom template tags maybe from another library, just like using import in Python.
*block *The {% block %} tag defines a block of content that a function can override in a child template.
*csfr_token *The {% csrf_token %} tag is significant in Django for form handling. It generates a hidden input field containing a CSRF token, which is required for secure form submissions.
*url *The {% url %} tag generates an absolute path reference( URL without domain name) based on the name of a view or a URL pattern.
*Use template inheritance *Django applications are meant to be reusable, and we can apply the same methodology to templates by inheriting regular HTML from other templates. A typical pattern is having a common base template for common aspects of your application, logged-in pages, logged-out pages, or places where significant changes are made to the underlying HTML. From our example below, base.html would contain most of the core structure that would make up each page, including the static CSS and Javascript, with blocks defined for an app or page-specific customizations.
Each child template then extends the base template as needed. For example, the 404.html inherits the base to render using the underlying CSS and JavaScript.
好像颇有价值的一个东西!
*Be Mindful of Handling Querysets *Handling queries within your templates can be a performance bottleneck for Django, depending on the complexities of your model definitions. Django’s templating system is tightly coupled with Django’s object-relational mapping layer, which returns data from the database. Without adequately considering this coupling, you may inadvertently cause the number of queries on each page load to jump to unmaintainable amounts. In some cases, this can cause the database to become too sluggish to operate certain pages on your site, or worse, crash and need to be restarted. Thankfully, Django provides mechanisms and patterns which we can use to make sure our templates are running as fast as possible, and we’re not killing the database server.