{% %} and {{ }} in Django

前端 未结 3 1491
北海茫月
北海茫月 2021-01-31 19:32

I am learning Django and came across 2 sets of special characters that I haven\'t seen used like this before. I can guess what they are used for in the examples, but don\'t unde

相关标签:
3条回答
  • 2021-01-31 20:03

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

    {{ foo }} - this is a placeholder in the template, for the variable foo that is passed to the template from a view.

    {% %} - when text is surrounded by these delimiters, it means that there is some special function or code running, and the result of that 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 feature of the template language itself that is being executed (like a for loop, or an if conditional). You can create your own extensions to the template language, which are called template tags.

    {{ foo|something }} - this is yet another syntax you may come across. The |something is a template filter. It is usually for transforming the result of the item on the left of the | symbol. For example {{ foo|title }}.

    You can read more about tags and filters which are referred to as template builtins in the documentation.

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

    The Python language doesn't have the same syntax, but it does have the concept of string templates which is a very simplified version of a template engine.

    0 讨论(0)
  • 2021-01-31 20:27

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

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

    And you use {{ }} to render variables in your template.

    0 讨论(0)
  • 2021-01-31 20:28

    {% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

    For more information, I suggest have a look at :

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

    0 讨论(0)
提交回复
热议问题