简体   繁体   中英

In Django how to render hello.html in base.html?

I am new to django and I misunderstand how to use templates.

I have aa file called base.html which I see as a parent to hello.html.

In hello.html I have this syntax:

{% extends "base.html" %}
{% block hello %}
<h1>hello</h1>
I should see this template. This is the hello.html template.
{% endblock %}

In base.html I have this syntax:

{% block hello %}{% endblock %}

It is my understanding that django should render hello.html inside of base.html

When I deploy my two html files, django ignores my syntax.

Question: How to render hello.html in base.html?

The files are visible inside of github:

https://github.com/danbikle/sof1231/blob/master/hello/templates/base.html

https://github.com/danbikle/sof1231/blob/master/hello/templates/hello.html

Also I deployed them to heroku with these commands:

heroku create sof1231
git push heroku master

You can see base.html deployed to https://sof1231.herokuapp.com

Again, How to render hello.html in base.html?

To render a template in another template, you use include :

base.html

{% include 'hello.html' %}

Your templates are designed to work with inheritance, and there is nothing wrong with the simplified templates that you show in your question (I didn't check those on github).

I think that your problem might be caused by your view rendering the base.html template, when it should instead be rendering the hello.html template. You should add your view code to your question so that this can be verified. Your view code should be something like this, which renders the child template hello.html :

def hello(request):
    template_variables = {'a': 1, 'b': 2}
    return render(request, 'hello.html', template_variables)

Another answer (which you have accepted) recommends using include . I don't think that include is the correct approach.

There is a difference between inheriting from a base template and simple inclusion of content from another file. One important benefit of template inheritance is that you can add common content (eg menu, side bars, footers, etc.) to a "base" template and then inherit from that base in child templates without duplicating the common content for each page. Another benefit is that the child templates can override content in the base templates, eg <title> . This allows you to markup areas of your layout in the base template (using block ) and then override the content of the block with other content. This is not possible with a simple include .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM