I'm working on a Django site that has multiple sections and subsections. I'd like to have several depths of template inheritance: a base template for the whole site, one base template for each section that inherits from the root base template, and so on. Here's a simplified version of my desired directory structure:
base.html
section1/
base.html
section2/
base.html
section3/
base.html
What I would desire is for all the files under section1/ to contain something like {% extends "base.html" %}, meaning they would extend section1/base.html. section1/base.html would contain something like {% extends "../base.html" %}, meaning that it would extend the root-level base file. However, I couldn't find anything in the documentation suggesting this was possible, and I couldn't get Django to distinguish between "../base.html" and "base.html". ({% extends "../base.html" %} throws an error.) I suppose one workaround would be to rename all base files base_SECTIONNAME.html, and update all the files that inherit from them, but I am concerned that this might become difficult to maintain as my site becomes bigger and sections change names, etc. I would prefer a solution that takes advantage of the natural hierarchy specified by directories and subdirectories.
Any ideas?
May be I oversee something, but all you want can be accomplished with the django template system. All extends calls are relative to template directories.
In order for all base.html files in subdirectories to extend base.html, you just have to put a {% extends "base.html" %} into the files. section1/base.html would would look like that.
{% extends "base.html" %}
{# ... rest of your code ...#}
Now, to get the files from section1 to extend section1/base.html you just have to put {% extends "section1/base.html" %} at the top of them. Same for section2, section3 and so on.
It is just that simple, but might not totally obvious in the documentation.
I hope, I understood your question.
The accepted answer will work, but I do recommend using variable names to keep track of section structure. My personal preference would be a context processor. If, for example, your site's section organization is transparently reflected in the url, try something like:
# It may be convenient to make this function live in or near your url conf.
def convert_url_path_to_folder_path(path):
# fill in the magic here
def sub_folder_available(request):
folder = convert_url_path_to_folder_path(request.path)
return {'subsection': folder, 'local_base':folder+'/base.html'}
Then in your template, just call
{% extends local_base %}
There are probably a dozen other ways to do this, but the main thing is to think about avoiding hard-coding the folder name into the template. This will get you a lot of mileage, especially since you can just drag and drop template between sections if they happen to be similar enough. Another thing you might add insert is:
def sub_folder_available(request):
folder = convert_url_path_to_folder_path(request.path)
# Check if local base exists:
if os.access(folder+'/base.html',os.F_OK):
base = folder+'/base.html'
else:
# revert to your global base
base = 'base.html'
return {'subsection': folder, 'base':base}
The nice advantage of this strategy is of course that you can get a fly-weight section up and running without any local base template at all.
You can use this library: https://github.com/vb64/django.templates.relative.path
Just write in your templates as follows:
{% load relative_path %}
{% extends ".base.html" %}
this will extend template "base.html", located in the same folder, where your template placed
{% load relative_path %}
{% extends "...base.html" %}
extend template "base.html", located at two levels higher
same things works with 'include' tag.
Related
Is there a syntax for referencing a local file? For example
Instead of having to write :
{% include 'user/project/task/task_detail/tab.html' %}
I want to write (from a template that's in the same directory as tab.html):
{% include './tab.html' %}
But the above raises jinja2.exceptions.TemplateNotFound
You can subclass Jinja's Environment and override the join_path() method to support import paths relative to the current directory.
class RelativeEnvironment(jinja2.Environment):
"""Override join_path() to enable relative template paths."""
def join_path(self, template, parent):
return os.path.join(os.path.dirname(parent), template)
However please mind that Jinja's mechanism of finding templates is designed in order to disambiguate templates' paths.
You can read more at https://jinja.palletsprojects.com/en/2.10.x/api/#jinja2.Environment.join_path
This question is a possible duplicate of How to include a template with relative path in Jinja2
Flask/j2 needs to know the structure to find a file, and it knowns the basic structure of app subfolders (static, templates etc.).
The best way is to put it in a static subfolders and then point at it using the url_for function:
..."{{ url_for('static', filename='<subfolder>/tab.html') }}"...
`
I have difficulties understanding the context behavior when including files in Jinja2 blocks. See this minimal example:
base.jinja2
{% set foo="bar" %}
{% block content %}
{% include 'include.jinja2' %}
{% endblock content %}
include.jinja2
{{ foo }}
Rendering base.jinja2 produces the error foo' is undefined.
When I move the declaration of foo into the content block, the code renders correctly. So does it, when I move the include statement outside the content block, when I remove the content block around the include statement, or when I replace the include statement with the file's contents.
Why is that? How can I use the global foo variable in the include file inside the content block?
Look at the link, section Block Nesting and Scope:
Blocks can be nested for more complex layouts. However, per default
blocks may not access variables from outer scopes:
The reason for this is that if the block is replaced by a child
template, a variable would appear that was not defined in the block or
passed to the context.
According to the document and starting with Jinja 2.2 you can change this behavior using scoped.
{% set foo="bar" %}
{% block content scoped %}
{% include 'include.jinja2' %}
{% endblock content %}
I agree that this is somehow weird, compared to what we are used to. But this is an intended feature.
Generally speaking, include is only passed the context. Since 2.1 it is
passed a derived context that is the original context + all the local
variables used before the include statement. This also means that if
you just use a variable from an outer scope, Jinja2 will track it as
local now and pass it to the derived context.
I have a video table with Foreign Keys that point to a document (multiple videos to one doc). I would like to check every element of that list, and on the first match with a query, enable an element (button that leads elsewhere). My attempts have been to use a for loop and then an if statement such that:
{% for vid in doc.video_set.all %}
{% if vid.query_data == 'match_term' %}
<-- button/link stuff -->
{% initialize variable %}
{% endif %}
{% endfor %}
the idea being if I initialized a variable I could add if "and variable is None" to the if statement and prevent future displays. However, after trying to use "set" and "with" to intialize variables I have been greeted with little more than error messages that seem to indicate these methods dont exist. How would I effectively achieve this functionality.
Django template language does not allow you to set variables like this. Your question is a bit confusing because you are trying to show how you would implement it in the Django template, rather than showing what you want the template to display. Here's a couple of suggestions:
If match_term is constant, you could add a method to your model.
class Doc(models.Model):
def first_match(self):
return self.video_set.filter(query_data='match_term').first()
Then use {{ doc.first_match }} in the template.
If match_term changes, then you might have to write a custom template tag.
I'm passing to Django's template a function, which returns some records.
I want to call this function and iterate over its result.
{% for item in my_func(10) %}
That doesn't work.
I've tried to set the function's return value to a variable and iterate over the variable, but there seems to be no way to set a variable in a Django template.
Is there any normal way to do it?
You cannot call a function that requires arguments in a template. Write a template tag or filter instead.
if you have an object you can define it as #property so you can get results without a call, e.g.
class Item:
#property
def results(self):
return something
then in the template:
<% for result in item.results %>
...
<% endfor %>
I'm passing to Django's template a function, which returns me some records
Why don't you pass to Django template the variable storing function's return value, instead of the function?
I've tried to set fuction's return value to a variable and iterate over variable, but there seems to be no way to set variable in Django template.
You should set variables in Django views instead of templates, and then pass them to the template.
By design, Django templates cannot call into arbitrary Python code. This is a security and safety feature for environments where designers write templates, and it also prevents business logic migrating into templates.
If you want to do this, you can switch to using Jinja2 templates (http://jinja.pocoo.org/docs/), or any other templating system you like that supports this. No other part of django will be affected by the templates you use, because it is intentionally a one-way process. You could even use many different template systems in the same project if you wanted.
What you could do is, create the "function" as another template file and then include that file passing the parameters to it.
Inside index.html
<h3> Latest Songs </h3>
{% include "song_player_list.html" with songs=latest_songs %}
Inside song_player_list.html
<ul>
{% for song in songs %}
<li>
<div id='songtile'>
<a href='/songs/download/{{song.id}}/'><i class='fa fa-cloud-download'></i> Download</a>
</div>
</li>
{% endfor %}
</ul>
I'm passing to Django's template a function, which returns some records.
I want to call this function and iterate over its result.
{% for item in my_func(10) %}
That doesn't work.
I've tried to set the function's return value to a variable and iterate over the variable, but there seems to be no way to set a variable in a Django template.
Is there any normal way to do it?
You cannot call a function that requires arguments in a template. Write a template tag or filter instead.
if you have an object you can define it as #property so you can get results without a call, e.g.
class Item:
#property
def results(self):
return something
then in the template:
<% for result in item.results %>
...
<% endfor %>
I'm passing to Django's template a function, which returns me some records
Why don't you pass to Django template the variable storing function's return value, instead of the function?
I've tried to set fuction's return value to a variable and iterate over variable, but there seems to be no way to set variable in Django template.
You should set variables in Django views instead of templates, and then pass them to the template.
By design, Django templates cannot call into arbitrary Python code. This is a security and safety feature for environments where designers write templates, and it also prevents business logic migrating into templates.
If you want to do this, you can switch to using Jinja2 templates (http://jinja.pocoo.org/docs/), or any other templating system you like that supports this. No other part of django will be affected by the templates you use, because it is intentionally a one-way process. You could even use many different template systems in the same project if you wanted.
What you could do is, create the "function" as another template file and then include that file passing the parameters to it.
Inside index.html
<h3> Latest Songs </h3>
{% include "song_player_list.html" with songs=latest_songs %}
Inside song_player_list.html
<ul>
{% for song in songs %}
<li>
<div id='songtile'>
<a href='/songs/download/{{song.id}}/'><i class='fa fa-cloud-download'></i> Download</a>
</div>
</li>
{% endfor %}
</ul>