Django Template Language
A context is a “variable name” -> “variable value” mapping that is passed to a template. A template renders a context by replacing the variable “holes” with values from the context and executing all block tags.
5 flashcards · Programming Languages · by lakesare
What is this syntax for: {% ... %} ?
Block tag. For example, a block tag can output content, serve as a control structure (an “if” statement or “for” loop), grab content from a database or enable access to other template tags.{% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %}
What is this syntax for: {{ ... }} ?
Variable. A variable is a symbol within a template that outputs a value.My first name is {{ first_name }}. My last name is {{ last_name }}.
How to create a default <html> layout that you'll render your template into? /posts/views.py: from django.shortcuts import render def index(request): return render(request, 'posts/index.html')
/posts/templates/posts/layout.html: <html> <head><head/> <body> {% block content %} {% endblock %} </body> <html> /posts/templates/posts/index.html: {% extends 'posts/layout.html' %} {% block content %} <h1>Hello from index.html</h1> {% endblock %}
How to pass a variable from controller to the template?
/posts/views.py: from django.shortcuts import render def index(request): context = { 'hi': 'hello' } return render(request, 'posts/index.html', context) /posts/templates/posts/index.html: <h1>{{ hi }}</h1>
How to create a partial in Django?
/_my_partials/hi.html: <h1>{{ a }}<h1> /posts/templates/posts/index.html: {% include '_my_partials/hi.html' with a="b" %} We can use the with option, or variables already present in out template will get included in the partial. Links: https://stackoverflow.com/a/13926418/3192470