Django project base template

徘徊边缘 提交于 2019-12-18 10:14:14

问题


Can I create a base template for my project which all apps can draw from? Or do I have to create a base template for each app? And if I wanted them to be the same I'd just copy them?


回答1:


Sure you can. A quick example of a base.html

<!DOCTYPE html>
<html>
    <head>
        <title>My Project</title>
    </head>

    <body>
    {% block content %}{% endblock content %}
    </body>
</html>

And say you have a app called myapp with a view.html page,

{% extends "base.html" %}

{% block content %}
    <h2>Content for My App</h2>
    <p>Stuff etc etc.</p>
{% endblock content %}

Take some time to read the docs for more information




回答2:


There is some problem in last answer and here is the correct one; you must have Base.html like this:

{% load staticfiles %}

<!DOCTYPE html>
<html>
<head>
    <title>My Project</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>

and also for index.html

{% extend "appname/base.html" %}
{% block content %}
     <h1>test</h1>
{% endblock %}



回答3:


Yes you can absolutely do that. By using extends and include template tags in your Django templates.

I am starting to learn Django and recently figured this out. My code is at Github if you are interested in taking a look at how I structure Django templates to inherit from a base.html and then include common stuff such as navbar and header, footer etc.




回答4:


Yes, you can create a base template for your project that other apps will extend. Check @Kenny_Shen answer on how.

Just wanted to add two notes if you are concerned about app isolation.

  1. If you do not want your app to rely on the "base.html" naming convention, you can inject the actual name with a variable, take a look at: How do I use Django's template extends variable? for details,

  2. You might want to name the app template block to something else, not "content" to avoid collisions with other apps.



来源:https://stackoverflow.com/questions/14720464/django-project-base-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!