Django Django Templates 1 — Questions and Answers
Question 1: What syntax is used to output a variable in a Django template?
- {{ variable }} (Correct answer)
- {% variable %}
- <% variable %>
- ${variable}
Correct answer: {{ variable }}
Double curly braces {{ }} are the Django template tag for rendering variable values; single curly-percent {% %} is used for block tags.
Question 2: Which template tag is used to extend a base template in Django?
- {% extends 'base.html' %} (Correct answer)
- {% include 'base.html' %}
- {% inherit 'base.html' %}
- {% parent 'base.html' %}
Correct answer: {% extends 'base.html' %}
{% extends %} must be the first tag in a child template and tells Django to use the named template as the parent layout.
Question 3: What does the `{% block %}` tag do in Django templates?
- Defines a named region in a parent template that child templates can override (Correct answer)
- Loops over a list of items
- Conditionally renders content
- Includes a static file
Correct answer: Defines a named region in a parent template that child templates can override
{% block name %}...{% endblock %} defines a replaceable region in a parent template, which child templates override using the same block name.
Question 4: How do you apply a template filter to a variable in Django?
- {{ value|filtername }} (Correct answer)
- {{ value.filtername }}
- {% filter value %}
- {{ filtername(value) }}
Correct answer: {{ value|filtername }}
The pipe character | applies a template filter to a variable, e.g., {{ name|upper }} converts the name to uppercase.
Question 5: Which Django template filter converts a string to all uppercase?
- upper (Correct answer)
- capitalize
- strtoupper
- upcase
Correct answer: upper
The upper filter converts all characters in the string to uppercase, e.g., {{ 'hello'|upper }} outputs 'HELLO'.
Question 6: What does the `{% include %}` tag do in Django templates?
- Renders another template and inserts its output into the current template (Correct answer)
- Inherits from a parent template
- Loads a template tag library
- Imports a Python module
Correct answer: Renders another template and inserts its output into the current template
{% include 'snippet.html' %} renders the named template with the current context and inserts the result inline, useful for reusable partials.
What syntax is used to output a variable in a Django template?