{%%} and {{}} in Django

I am learning Django and came across two sets of special characters that I had not seen before. I can guess that they are used in the examples, but do not understand their capabilities.

It:

  • {% if registered %}
  • {{ user_form.as_p }}

I added if registered and user_form.as_p for context. I'm only interested in the parts {% %} and {{ }} .

  • Are they only used in Django or are they also used in Python?
  • What is the meaning of each?
  • Are there other similar character sets?
+7
django
source share
3 answers

These are special tokens that appear in django templates. You can read more about syntax in the link to the django template language in the documentation.

{{ foo }} is the placeholder in the template, for the variable foo, which is passed to the template from the view.

{% %} - when the text is surrounded by these delimiters, it means that there is some special function or code, and the result of this will be placed here. It is used when the text inside is not passed to the template from the view, but rather a function or function of the template language itself, which is executed (for example, a for loop or conditional if condition). You can create your own extensions for the template language, which are called template tags.

{{ foo|something }} is another syntax you may come across. |something is a template filter. This is usually a conversion of the result of the element to the left of the | . For example, {{ foo|title }} .

Read more about tags and filters called template builtins in the documentation.

This syntax is not unique to django - many other template languages ​​in Python (and some outside Python) have adopted a similar syntax.

Python does not have the same syntax, but has the concept of string patterns , which is a very simplified version of the engine pattern.

+11
source share

They are used in .html aka templates files. They are not python , they are part of the Django template engine .

You use {% %} for sentences such as: if and for , or for invoking tags such as: load , static , etc.

And you use {{ }} to visualize the variables in your template.

+2
source share

{%%} and {{}} are part of the Django template language. They are used to pass variables from views to a template. {%%} is mainly used when you have an expression called tags, and {{}} is used to easily access a variable.

For more information, I suggest taking a look at:

https://docs.djangoproject.com/en/1.9/ref/templates/language/#variables

+1
source share

All Articles