标签归档:templates

Django模板中的模数%

问题:Django模板中的模数%

我正在寻找一种使用django中的模运算符之类的方法。我想做的是在循环中的每个第四个元素中添加一个类名。

使用模数,它看起来像这样:

{% for p in posts %}
    <div class="post width1 height2 column {% if forloop.counter0 % 4 == 0 %}first{% endif %}}">
        <div class="preview">

        </div>
        <div class="overlay">

        </div>
        <h2>p.title</h2>
    </div>
{% endfor %}

当然,这是行不通的,因为%是保留字符。还有其他方法吗?

I’m looking for a way to use something like the modulus operator in django. What I am trying to do is to add a classname to every fourth element in a loop.

With modulus it would look like this:

{% for p in posts %}
    <div class="post width1 height2 column {% if forloop.counter0 % 4 == 0 %}first{% endif %}}">
        <div class="preview">

        </div>
        <div class="overlay">

        </div>
        <h2>p.title</h2>
    </div>
{% endfor %}

Of course this doesn’t work because % is a reserved character. Is there any other way to do this?


回答 0

您需要divisibleby(内置的django过滤器)。

{% for p in posts %}
    <div class="post width1 height2 column {% if forloop.counter0|divisibleby:4 %}first{% endif %}">
        <div class="preview">

        </div>
        <div class="overlay">

        </div>
        <h2>p.title</h2>
    </div>
{% endfor %}

You need divisibleby, a built-in django filter.

{% for p in posts %}
    <div class="post width1 height2 column {% if forloop.counter0|divisibleby:4 %}first{% endif %}">
        <div class="preview">

        </div>
        <div class="overlay">

        </div>
        <h2>p.title</h2>
    </div>
{% endfor %}

回答 1

您不能在Django模板标签中使用模数运算符,但是编写过滤器很容易做到这一点。这样的事情应该起作用:

@register.filter
def modulo(num, val):
    return num % val

然后:

{% ifequal forloop.counter0|modulo:4 0 %}

您甚至可以执行以下操作:

@register.filter
def modulo(num, val):
    return num % val == 0

然后:

{% if forloop.counter0|modulo:4 %}

或者,您可以使用cycle标签:

<div class="post width1 height2 column {% cycle 'first' '' '' '' %}">

You can’t use the modulus operator in Django template tags, but it would be easy enough to write a filter to do so. Something like this should work:

@register.filter
def modulo(num, val):
    return num % val

And then:

{% ifequal forloop.counter0|modulo:4 0 %}

You could even do something like this, instead:

@register.filter
def modulo(num, val):
    return num % val == 0

And then:

{% if forloop.counter0|modulo:4 %}

Or you could use the cycle tag:

<div class="post width1 height2 column {% cycle 'first' '' '' '' %}">

回答 2

听起来您应该只使用cycle标签。 内置模板标签

It sounds like you should just use the cycle tag. Built-in template tags


回答 3

引导行和列的示例。每4项新行。即使少于4个项目,也请关闭最后一行。

myapp / templatetags / my_tags.py

from django import template

register = template.Library()

@register.filter
def modulo(num, val):
    return num % val

html模板

{% load my_tags %}

{% for item in all_items %} 
    {% if forloop.counter|modulo:4 == 1 %}
        <div class="row">
    {% endif %}

        <div class="col-sm-3">
            {{ item }}
        </div>

    {% if forloop.last or forloop.counter|modulo:4 == 0 %}
        </div>
    {% endif %}

{% endfor %}

Bootstrap rows and columns example. New row every 4 items. Also close last row even if there are less than 4 items.

myapp/templatetags/my_tags.py

from django import template

register = template.Library()

@register.filter
def modulo(num, val):
    return num % val

html template

{% load my_tags %}

{% for item in all_items %} 
    {% if forloop.counter|modulo:4 == 1 %}
        <div class="row">
    {% endif %}

        <div class="col-sm-3">
            {{ item }}
        </div>

    {% if forloop.last or forloop.counter|modulo:4 == 0 %}
        </div>
    {% endif %}

{% endfor %}

应用程序未拾取.css文件(烧瓶/ python)

问题:应用程序未拾取.css文件(烧瓶/ python)

我正在渲染一个模板,尝试使用外部样式表进行样式设置。文件结构如下。

/app
    - app_runner.py
    /services
        - app.py 
    /templates
        - mainpage.html
    /styles
        - mainpage.css

mainpage.html看起来像这样

<html>
    <head>
        <link rel= "stylesheet" type= "text/css" href= "../styles/mainpage.css">
    </head>
    <body>
        <!-- content --> 

我的样式均未应用。它与html是我正在渲染的模板有关吗?python看起来像这样。

return render_template("mainpage.html", variables..)

我知道这很有效,因为我仍然能够渲染模板。但是,当我尝试将样式代码从html的“ head”标记中的“样式”块移动到外部文件时,所有样式消失了,留下了一个裸露的html页面。有人看到我的文件结构有任何错误吗?

I am rendering a template, that I am attempting to style with an external style sheet. File structure is as follows.

/app
    - app_runner.py
    /services
        - app.py 
    /templates
        - mainpage.html
    /styles
        - mainpage.css

mainpage.html looks like this

<html>
    <head>
        <link rel= "stylesheet" type= "text/css" href= "../styles/mainpage.css">
    </head>
    <body>
        <!-- content --> 

None of my styles are being applied though. Does it have something to do with the fact that the html is a template I am rendering? The python looks like this.

return render_template("mainpage.html", variables..)

I know this much is working, because I am still able to render the template. However, when I tried to move my styling code from a “style” block within the html’s “head” tag to an external file, all the styling went away, leaving a bare html page. Anyone see any errors with my file structure?


回答 0

您需要有一个“静态”文件夹设置(用于css / js文件),除非您在Flask初始化期间专门覆盖了它。我假设您没有覆盖它。

您的CSS目录结构应类似于:

/app
    - app_runner.py
    /services
        - app.py 
    /templates
        - mainpage.html
    /static
        /styles
            - mainpage.css

请注意,您的/ styles目录应位于/ static下

然后做

<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainpage.css') }}">

Flask现在将在static / styles / mainpage.css下查找css文件

You need to have a ‘static’ folder setup (for css/js files) unless you specifically override it during Flask initialization. I am assuming you did not override it.

Your directory structure for css should be like:

/app
    - app_runner.py
    /services
        - app.py 
    /templates
        - mainpage.html
    /static
        /styles
            - mainpage.css

Notice that your /styles directory should be under /static

Then, do this

<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainpage.css') }}">

Flask will now look for the css file under static/styles/mainpage.css


回答 1

在jinja2模板(flask使用的模板)中,使用

href="{{ url_for('static', filename='mainpage.css')}}"

但是,这些static文件通常位于static文件夹中,除非另有配置。

In jinja2 templates (which flask uses), use

href="{{ url_for('static', filename='mainpage.css')}}"

The static files are usually in the static folder, though, unless configured otherwise.


回答 2

我已经阅读了多个主题,但都没有解决人们正在描述的问题,我也经历过。

我什至尝试离开conda并使用pip升级到python 3.7,我尝试了所有建议的编码,但均未解决。

这就是原因(问题):

默认情况下,python / flask在以下文件夹结构中搜索静态文件和模板:

/Users/username/folder_one/folder_two/ProjectName/src/app_name/<static>
 and 
/Users/username/folder_one/folder_two/ProjectName/src/app_name/<template>

您可以使用Pycharm(或其他任何工具)上的调试器自己进行验证,并检查应用程序上的值(app = Flask(name))并搜索teamplate_folder和static_folder

为了解决这个问题,您必须在创建应用程序时指定值,如下所示:

TEMPLATE_DIR = os.path.abspath('../templates')
STATIC_DIR = os.path.abspath('../static')

# app = Flask(__name__) # to make the app run without any
app = Flask(__name__, template_folder=TEMPLATE_DIR, static_folder=STATIC_DIR)

路径TEMPLATE_DIR和STATIC_DIR取决于文件应用程序所在的位置。就我而言,请参见图片,它位于src下的文件夹中。

您可以根据需要更改模板和静态文件夹,并在应用程序= Flask上注册…

实际上,当我弄乱文件夹时,我已经开始遇到问题,有时却无法正常工作。这可以彻底解决问题

html代码如下所示:

<link href="{{ url_for('static', filename='libraries/css/bootstrap.css') }}" rel="stylesheet" type="text/css" >

这个代码

这里的文件夹结构

I have read multiple threads and none of them fixed the issue that people are describing and I have experienced too.

I have even tried to move away from conda and use pip, to upgrade to python 3.7, i have tried all coding proposed and none of them fixed.

And here is why (the problem):

by default python/flask search the static and the template in a folder structure like:

/Users/username/folder_one/folder_two/ProjectName/src/app_name/<static>
 and 
/Users/username/folder_one/folder_two/ProjectName/src/app_name/<template>

you can verify by yourself using the debugger on Pycharm (or anything else) and check the values on the app (app = Flask(name)) and search for teamplate_folder and static_folder

in order to fix this, you have to specify the values when creating the app something like this:

TEMPLATE_DIR = os.path.abspath('../templates')
STATIC_DIR = os.path.abspath('../static')

# app = Flask(__name__) # to make the app run without any
app = Flask(__name__, template_folder=TEMPLATE_DIR, static_folder=STATIC_DIR)

the path TEMPLATE_DIR and STATIC_DIR depend on where the file app is located. in my case, see the picture, it was located within a folder under src.

you can change the template and static folders as you wish and register on the app = Flask…

In truth, I have started experiencing the problem when messing around with folder and at times worked at times not. this fixes the problem once and for all

the html code looks like this:

<link href="{{ url_for('static', filename='libraries/css/bootstrap.css') }}" rel="stylesheet" type="text/css" >

This the code

Here the structure of the folders


回答 3

仍然有下面由codegeek提供的解决方案后的问题:
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainpage.css') }}">

Google Chrome浏览器中,按下重新加载按钮(F5)不会重新加载静态文件。如果遵循了公认的解决方案,但仍然看不到对CSS所做的更改,请按ctrl + shift + R忽略缓存的文件并重新加载静态文件。

Firefox中,按下重新加载按钮会出现以重新加载静态文件。

Edge中,按刷新按钮不会重新加载静态文件。按ctrl + shift + R应该忽略缓存的文件并重新加载静态文件。但是,这在我的计算机上不起作用。

Still having problems after following the solution provided by codegeek:
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/mainpage.css') }}"> ?

In Google Chrome pressing the reload button (F5) will not reload the static files. If you have followed the accepted solution but still don’t see the changes you have made to CSS, then press ctrl + shift + R to ignore cached files and reload the static files.

In Firefox pressing the reload button appears to reload the static files.

In Edge pressing the refresh button does not reload the static file. Pressing ctrl + shift + R is supposed to ignore cached files and reload the static files. However this does not work on my computer.


回答 4

我正在运行flask的1.0.2版本。上面的文件结构对我不起作用,但是我找到了一个可以的文件结构,如下所示:

     app_folder/ flask_app.py/ static/ style.css/ templates/
     index.html

(请注意,“静态”和“模板”是文件夹,应命名为完全相同的名称。)

要检查您正在运行的烧瓶版本,应在终端中打开Python并相应地键入以下内容:

进口烧瓶

烧瓶-版本

I’m running version 1.0.2 of flask right now. The above file structures did not work for me, but I found one that did, which are as follows:

     app_folder/ flask_app.py/ static/ style.css/ templates/
     index.html

(Please note that ‘static’ and ‘templates’ are folders, which should be named exactly the same thing.)

To check what version of flask you are running, you should open Python in terminal and type the following accordingly:

import flask

flask –version


回答 5

烧瓶项目的结构不同。正如您所提到的,项目结构是相同的,但是唯一的问题是样式文件夹。样式文件夹必须位于静态文件夹内。

static/styles/style.css

The flask project structure is different. As you mentioned in question the project structure is the same but the only problem is wit the styles folder. Styles folder must come within the static folder.

static/styles/style.css

回答 6

还有一点要添加到该线程上。

如果在.css文件名中添加下划线,则将无法使用。

One more point to add on to this thread.

If you add an underscore in your .css file name, then it wouldn’t work.


回答 7

还有一点要添加。除了上面提到的答案外,请确保将以下行添加到app.py文件中:

app = Flask(__name__, static_folder="your path to static")

否则,flask将无法检测到静态文件夹。

One more point to add.Along with above upvoted answers, please make sure the below line is added to app.py file:

app = Flask(__name__, static_folder="your path to static")

Otherwise flask will not be able to detect static folder.


回答 8

如果以上任何方法都不起作用,并且您的代码是完美的,则请按Ctrl + F5尝试进行强制刷新。它将清除所有机会,然后重新加载文件。它为我工作。

If any of the above method is not working and you code is perfect then try hard refreshing by pressing Ctrl + F5. It will clear all the chaces and then reload file. It worked for me.


回答 9

我很确定它类似于Laravel模板,这就是我的方法。

<link rel="stylesheet" href="/folder/stylesheets/stylesheet.css" />

引用: CSS文件路径问题

一个简单的flask应用程序,它从.html文件读取其内容。外部样式表被阻止?

I’m pretty sure it’s similar to Laravel template, this is how I did mine.

<link rel="stylesheet" href="/folder/stylesheets/stylesheet.css" />

Referred: CSS file pathing problem

Simple flask application that reads its content from a .html file. External style sheet being blocked?


如何直接转到Django的urls.py中的模板?

问题:如何直接转到Django的urls.py中的模板?

我希望它转到模板robots.txt,而不是views.py。

Instead of going to views.py, I want it to go to to a template, robots.txt.


回答 0

Django 2.0以上

使用基于类的通用视图,但要使用django 2.0+模式进行注册。

from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
    path('foo/', TemplateView.as_view(template_name='foo.html'))
]

https://docs.djangoproject.com/zh-CN/2.0/ref/class-based-views/base/#templateview

Django 1.5以上

使用基于类的通用视图。

from django.views.generic import TemplateView

urlpatterns = patterns('',
    (r'^foo/$', TemplateView.as_view(template_name='foo.html')),
)

Django <= 1.4

文档:https : //docs.djangoproject.com/zh-CN/1.4/ref/generic-views/#django-views-generic-simple-direct-to-template

urlpatterns = patterns('django.views.generic.simple',
    (r'^foo/$',             'direct_to_template', {'template': 'foo_index.html'}),
    (r'^foo/(?P<id>\d+)/$', 'direct_to_template', {'template': 'foo_detail.html'}),
)

Django 2.0+

Use the class based generic views but register with the django 2.0+ pattern.

from django.urls import path
from django.views.generic import TemplateView

urlpatterns = [
    path('foo/', TemplateView.as_view(template_name='foo.html'))
]

https://docs.djangoproject.com/en/2.0/ref/class-based-views/base/#templateview

Django 1.5+

Use the class based generic views.

from django.views.generic import TemplateView

urlpatterns = patterns('',
    (r'^foo/$', TemplateView.as_view(template_name='foo.html')),
)

Django <= 1.4

Docs: https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-simple-direct-to-template

urlpatterns = patterns('django.views.generic.simple',
    (r'^foo/$',             'direct_to_template', {'template': 'foo_index.html'}),
    (r'^foo/(?P<id>\d+)/$', 'direct_to_template', {'template': 'foo_detail.html'}),
)

回答 1

有关此网站的最新哑剧类型的最新更新,包括:

http://www.techstricks.com/adding-robots-txt-to-your-django-project/

from django.conf.urls import url
from django.views.generic import TemplateView

urlpatterns = [
    #... your project urls
    url(r'^robots.txt$', TemplateView.as_view(template_name="robots.txt", content_type="text/plain"), name="robots_file")
]

A further update for more recent versions and including mime type from this site:

http://www.techstricks.com/adding-robots-txt-to-your-django-project/

from django.conf.urls import url
from django.views.generic import TemplateView

urlpatterns = [
    #... your project urls
    url(r'^robots.txt$', TemplateView.as_view(template_name="robots.txt", content_type="text/plain"), name="robots_file")
]

即使模板文件存在,Flask也会引发TemplateNotFound错误

问题:即使模板文件存在,Flask也会引发TemplateNotFound错误

我正在尝试渲染文件home.html。该文件存在于我的项目中,但是jinja2.exceptions.TemplateNotFound: home.html当我尝试渲染它时,我一直在获取它。Flask为什么找不到我的模板?

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')
/myproject
    app.py
    home.html

I am trying to render the file home.html. The file exists in my project, but I keep getting jinja2.exceptions.TemplateNotFound: home.html when I try to render it. Why can’t Flask find my template?

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')
/myproject
    app.py
    home.html

回答 0

您必须在正确的位置创建模板文件。在templatespython模块旁边的子目录中。

该错误表明目录中没有home.html文件templates/。确保在与python模块相同的目录中创建了该目录,并且确实将home.html文件放在该子目录中。如果您的应用是软件包,则应在软件包创建模板文件夹。

myproject/
    app.py
    templates/
        home.html
myproject/
    mypackage/
        __init__.py
        templates/
            home.html

另外,如果您将模板文件夹命名为其他名称,templates并且不想将其重命名为默认名称,则可以告诉Flask使用该其他目录。

app = Flask(__name__, template_folder='template')  # still relative to module

你可以问烧瓶解释它是如何试图找到一个给定的模板,通过设置EXPLAIN_TEMPLATE_LOADING选项True。对于每个加载的模板,您将获得一个报告记录到Flaskapp.logger的级别INFO

搜索成功后的样子:在此示例中,foo/bar.html模板扩展了base.html模板,因此有两个搜索:

[2019-06-15 16:03:39,197] INFO in debughelpers: Locating template "foo/bar.html":
    1: trying loader of application "flaskpackagename"
       class: jinja2.loaders.FileSystemLoader
       encoding: 'utf-8'
       followlinks: False
       searchpath:
         - /.../project/flaskpackagename/templates
       -> found ('/.../project/flaskpackagename/templates/foo/bar.html')
[2019-06-15 16:03:39,203] INFO in debughelpers: Locating template "base.html":
    1: trying loader of application "flaskpackagename"
       class: jinja2.loaders.FileSystemLoader
       encoding: 'utf-8'
       followlinks: False
       searchpath:
         - /.../project/flaskpackagename/templates
       -> found ('/.../project/flaskpackagename/templates/base.html')

蓝图也可以注册自己的模板目录,但这不是必需的,如果您使用蓝图可以更轻松地在逻辑单元之间拆分较大的项目。即使在每个蓝图中使用其他路径,也始终会首先搜索Flask应用程序主模板目录。

You must create your template files in the correct location; in the templates subdirectory next to your python module.

The error indicates that there is no home.html file in the templates/ directory. Make sure you created that directory in the same directory as your python module, and that you did in fact put a home.html file in that subdirectory. If your app is a package, the templates folder should be created inside the package.

myproject/
    app.py
    templates/
        home.html
myproject/
    mypackage/
        __init__.py
        templates/
            home.html

Alternatively, if you named your templates folder something other than templates and don’t want to rename it to the default, you can tell Flask to use that other directory.

app = Flask(__name__, template_folder='template')  # still relative to module

You can ask Flask to explain how it tried to find a given template, by setting the EXPLAIN_TEMPLATE_LOADING option to True. For every template loaded, you’ll get a report logged to the Flask app.logger, at level INFO.

This is what it looks like when a search is successful; in this example the foo/bar.html template extends the base.html template, so there are two searches:

[2019-06-15 16:03:39,197] INFO in debughelpers: Locating template "foo/bar.html":
    1: trying loader of application "flaskpackagename"
       class: jinja2.loaders.FileSystemLoader
       encoding: 'utf-8'
       followlinks: False
       searchpath:
         - /.../project/flaskpackagename/templates
       -> found ('/.../project/flaskpackagename/templates/foo/bar.html')
[2019-06-15 16:03:39,203] INFO in debughelpers: Locating template "base.html":
    1: trying loader of application "flaskpackagename"
       class: jinja2.loaders.FileSystemLoader
       encoding: 'utf-8'
       followlinks: False
       searchpath:
         - /.../project/flaskpackagename/templates
       -> found ('/.../project/flaskpackagename/templates/base.html')

Blueprints can register their own template directories too, but this is not a requirement if you are using blueprints to make it easier to split a larger project across logical units. The main Flask app template directory is always searched first even when using additional paths per blueprint.


回答 1

我认为Flask默认使用目录模板。因此,您的代码应该假设这是您的hello.py

from flask import Flask,render_template

app=Flask(__name__,template_folder='template')


@app.route("/")
def home():
    return render_template('home.html')

@app.route("/about/")
def about():
    return render_template('about.html')

if __name__=="__main__":
    app.run(debug=True)

你的工作空间结构就像

project/
    hello.py        
    template/
         home.html
         about.html    
    static/
           js/
             main.js
           css/
               main.css

您还创建了两个HTML文件,名称分别为home.html和about.html,并将它们放在模板文件夹中。

I think Flask uses the directory templates by default. So your code should be suppose this is your hello.py

from flask import Flask,render_template

app=Flask(__name__,template_folder='template')


@app.route("/")
def home():
    return render_template('home.html')

@app.route("/about/")
def about():
    return render_template('about.html')

if __name__=="__main__":
    app.run(debug=True)

And you work space structure like

project/
    hello.py        
    template/
         home.html
         about.html    
    static/
           js/
             main.js
           css/
               main.css

also you have create two html files with name of home.html and about.html and put those files in template folder.


回答 2

(请注意,上面为文件/项目结构提供的已接受答案是绝对正确的。)

也..

除了正确设置项目文件结构外,我们还必须告诉flask查找目录层次结构的适当级别。

例如..

    app = Flask(__name__, template_folder='../templates')
    app = Flask(__name__, template_folder='../templates', static_folder='../static')

从开始../向后移动一个目录,然后从那里开始。

从开始../../向后移动两个目录,然后从那里开始(依此类推…)。

希望这可以帮助

(Please note that the above accepted Answer provided for file/project structure is absolutely correct.)

Also..

In addition to properly setting up the project file structure, we have to tell flask to look in the appropriate level of the directory hierarchy.

for example..

    app = Flask(__name__, template_folder='../templates')
    app = Flask(__name__, template_folder='../templates', static_folder='../static')

Starting with ../ moves one directory backwards and starts there.

Starting with ../../ moves two directories backwards and starts there (and so on…).

Hope this helps


回答 3

我不知道为什么,但是我不得不使用以下文件夹结构。我将“模板”提高了一层。

project/
    app/
        hello.py
        static/
            main.css
    templates/
        home.html
    venv/

这可能表明在其他地方配置错误,但是我无法弄清楚那是什么,并且这可行。

I don’t know why, but I had to use the following folder structure instead. I put “templates” one level up.

project/
    app/
        hello.py
        static/
            main.css
    templates/
        home.html
    venv/

This probably indicates a misconfiguration elsewhere, but I couldn’t figure out what that was and this worked.


回答 4

检查:

  1. 模板文件具有正确的名称
  2. 模板文件位于一个名为 templates
  3. 您传递给的名称render_template是相对于模板目录的(index.html直接位于模板目录中,位于模板目录中auth/login.html的auth目录下。)
  4. 您可能没有与您的应用同名的子目录,或者模板目录位于该子目录中。

如果这不起作用,请打开调试(app.debug = True),这可能有助于找出问题所在。

Check that:

  1. the template file has the right name
  2. the template file is in a subdirectory called templates
  3. the name you pass to render_template is relative to the template directory (index.html would be directly in the templates directory, auth/login.html would be under the auth directory in the templates directory.)
  4. you either do not have a subdirectory with the same name as your app, or the templates directory is inside that subdir.

If that doesn’t work, turn on debugging (app.debug = True) which might help figure out what’s wrong.


回答 5

如果从已安装的程序包运行代码,请确保目录中存在模板文件<python root>/lib/site-packages/your-package/templates


一些细节:

就我而言,我试图运行项目flask_simple_ui的示例,并且jinja总是会说

jinja2.exceptions.TemplateNotFound:form.html

诀窍是示例程序将导入已安装的软件包flask_simple_ui。而ninja从内部的包装使用的根目录查找包路径,在我的情况下被使用...python/lib/site-packages/flask_simple_ui,而不是os.getcwd() 作为一个期望的那样。

不幸的是,它setup.py存在一个错误,并且不会复制任何html文件,包括missing form.html。一旦修复setup.pyTemplateNotFound的问题就消失了。

希望对您有所帮助。

If you run your code from an installed package, make sure template files are present in directory <python root>/lib/site-packages/your-package/templates.


Some details:

In my case I was trying to run examples of project flask_simple_ui and jinja would always say

jinja2.exceptions.TemplateNotFound: form.html

The trick was that sample program would import installed package flask_simple_ui. And ninja being used from inside that package is using as root directory for lookup the package path, in my case ...python/lib/site-packages/flask_simple_ui, instead of os.getcwd() as one would expect.

To my bad luck, setup.py has a bug and doesn’t copy any html files, including the missing form.html. Once I fixed setup.py, the problem with TemplateNotFound vanished.

I hope it helps someone.


回答 6

我遇到了同样的错误,事实证明,我唯一做错的就是将我的“模板”文件夹命名为“模板”而不命名为“ s”。更改它正常工作后,不知道为什么它是东西,但是它是。

I had the same error turns out the only thing i did wrong was to name my ‘templates’ folder,’template’ without ‘s’. After changing that it worked fine,dont know why its a thing but it is.


回答 7

当使用render_template()函数时,它将尝试在名为template的文件夹中搜索模板,并在以下情况下引发jinja2.exceptions.TemplateNotFound错误:

  1. html文件不存在或
  2. 当模板文件夹不存在时

解决问题:

在python文件所在的目录中创建一个带有名称模板的文件夹,并将创建的html文件放置在模板文件夹中。

When render_template() function is used it tries to search for template in the folder called templates and it throws error jinja2.exceptions.TemplateNotFound when :

  1. the html file do not exist or
  2. when templates folder do not exist

To solve the problem :

create a folder with name templates in the same directory where the python file is located and place the html file created in the templates folder.


回答 8

您需要将所有.html文件放在python模块旁边的模板文件夹中。并且,如果您的html文件中使用了任何图像,则需要将所有文件放在名为static的文件夹中

在以下结构中

project/
    hello.py
    static/
        image.jpg
        style.css
    templates/
        homepage.html
    virtual/
        filename.json

You need to put all you .html files in the template folder next to your python module. And if there are any images that you are using in your html files then you need put all your files in the folder named static

In the following Structure

project/
    hello.py
    static/
        image.jpg
        style.css
    templates/
        homepage.html
    virtual/
        filename.json

回答 9

另一种选择是设置,root_path它可以解决模板和静态文件夹的问题。

root_path = Path(sys.executable).parent if getattr(sys, 'frozen', False) else Path(__file__).parent
app = Flask(__name__.split('.')[0], root_path=root_path)

如果您直接通过渲染模板Jinja2,则可以这样写:

ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(str(root_path / 'templates')))
template = ENV.get_template(your_template_name)

Another alternative is to set the root_path which fixes the problem both for templates and static folders.

root_path = Path(sys.executable).parent if getattr(sys, 'frozen', False) else Path(__file__).parent
app = Flask(__name__.split('.')[0], root_path=root_path)

If you render templates directly via Jinja2, then you write:

ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(str(root_path / 'templates')))
template = ENV.get_template(your_template_name)

在没有其他Django的情况下如何使用Django模板?

问题:在没有其他Django的情况下如何使用Django模板?

我想在我的(Python)代码中使用Django模板引擎,但是我没有构建基于Django的网站。如何在没有settings.py文件(和其他文件)且没有设置DJANGO_SETTINGS_MODULE环境变量的情况下使用它?

如果我运行以下代码:

>>> import django.template
>>> from django.template import Template, Context
>>> t = Template('My name is {{ my_name }}.')

我得到:

ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

I want to use the Django template engine in my (Python) code, but I’m not building a Django-based web site. How do I use it without having a settings.py file (and others) and having to set the DJANGO_SETTINGS_MODULE environment variable?

If I run the following code:

>>> import django.template
>>> from django.template import Template, Context
>>> t = Template('My name is {{ my_name }}.')

I get:

ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

回答 0

解决方案很简单。它实际上有据可查,但不太容易找到。(我必须仔细研究-当我尝试了几种其他的Google搜索时并没有出现。)

以下代码有效:

>>> from django.template import Template, Context
>>> from django.conf import settings
>>> settings.configure()
>>> t = Template('My name is {{ my_name }}.')
>>> c = Context({'my_name': 'Daryl Spitzer'})
>>> t.render(c)
u'My name is Daryl Spitzer.'

有关您可能要定义的某些设置(作为要配置的关键字参数)的说明,请参阅Django文档(上文链接)。

The solution is simple. It’s actually well documented, but not too easy to find. (I had to dig around — it didn’t come up when I tried a few different Google searches.)

The following code works:

>>> from django.template import Template, Context
>>> from django.conf import settings
>>> settings.configure()
>>> t = Template('My name is {{ my_name }}.')
>>> c = Context({'my_name': 'Daryl Spitzer'})
>>> t.render(c)
u'My name is Daryl Spitzer.'

See the Django documentation (linked above) for a description of some of the settings you may want to define (as keyword arguments to configure).


回答 1

Jinja2 语法与Django几乎相同,只是差别很小,而且您获得了功能更强大的模板引擎,该引擎还将模板编译为字节码(FAST!)。

我使用它来进行模板化,包括在Django本身中,它非常好。如果缺少某些所需功能,您也可以轻松编写扩展名。

这是代码生成的一些演示:

>>> import jinja2
>>> print jinja2.Environment().compile('{% for row in data %}{{ row.name | upper }}{% endfor %}', raw=True) 
from __future__ import division
from jinja2.runtime import LoopContext, Context, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join
name = None

def root(context, environment=environment):
    l_data = context.resolve('data')
    t_1 = environment.filters['upper']
    if 0: yield None
    for l_row in l_data:
        if 0: yield None
        yield unicode(t_1(environment.getattr(l_row, 'name')))

blocks = {}
debug_info = '1=9'

Jinja2 syntax is pretty much the same as Django’s with very few differences, and you get a much more powerfull template engine, which also compiles your template to bytecode (FAST!).

I use it for templating, including in Django itself, and it is very good. You can also easily write extensions if some feature you want is missing.

Here is some demonstration of the code generation:

>>> import jinja2
>>> print jinja2.Environment().compile('{% for row in data %}{{ row.name | upper }}{% endfor %}', raw=True) 
from __future__ import division
from jinja2.runtime import LoopContext, Context, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join
name = None

def root(context, environment=environment):
    l_data = context.resolve('data')
    t_1 = environment.filters['upper']
    if 0: yield None
    for l_row in l_data:
        if 0: yield None
        yield unicode(t_1(environment.getattr(l_row, 'name')))

blocks = {}
debug_info = '1=9'

回答 2

您要使用Django模板的任何特殊原因?无论神社元史是,在我看来,优越。


如果您确实愿意,请参见中的Django文档settings.py。特别是“使用设置而不设置DJANGO_SETTINGS_MODULE”部分。使用这样的东西:

from django.conf import settings
settings.configure (FOO='bar') # Your settings go here

Any particular reason you want to use Django’s templates? Both Jinja and Genshi are, in my opinion, superior.


If you really want to, then see the Django documentation on settings.py. Especially the section “Using settings without setting DJANGO_SETTINGS_MODULE“. Use something like this:

from django.conf import settings
settings.configure (FOO='bar') # Your settings go here

回答 3

我还建议jinja2。关于vs. 有一篇不错的文章,其中提供了一些详细信息,说明您为什么偏爱后者。djangojinja2

I would also recommend jinja2. There is a nice article on django vs. jinja2 that gives some in-detail information on why you should prefere the later.


回答 4

根据Jinja文档,Python 3支持仍处于试验阶段。因此,如果您使用的是Python 3,而性能不是问题,则可以使用django的内置模板引擎。

Django 1.8引入了对多个模板引擎的支持,这需要更改模板的初始化方式。您必须显式配置settings.DEBUGdjango提供的默认模板引擎使用的模板。这是不使用django其余部分即可使用模板的代码。

from django.template import Template, Context
from django.template.engine import Engine

from django.conf import settings
settings.configure(DEBUG=False)

template_string = "Hello {{ name }}"
template = Template(template_string, engine=Engine())
context = Context({"name": "world"})
output = template.render(context) #"hello world"

According to the Jinja documentation, Python 3 support is still experimental. So if you are on Python 3 and performance is not an issue, you can use django’s built in template engine.

Django 1.8 introduced support for multiple template engines which requires a change to the way templates are initialized. You have to explicitly configure settings.DEBUG which is used by the default template engine provided by django. Here’s the code to use templates without using the rest of django.

from django.template import Template, Context
from django.template.engine import Engine

from django.conf import settings
settings.configure(DEBUG=False)

template_string = "Hello {{ name }}"
template = Template(template_string, engine=Engine())
context = Context({"name": "world"})
output = template.render(context) #"hello world"

回答 5

除了其他人写的东西之外,如果要在Django> 1.7上使用Django模板,则必须给您的settings.configure(…)调用TEMPLATES变量,然后像这样调用django.setup():

from django.conf import settings

settings.configure(TEMPLATES=[
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['.'], # if you want the templates from a file
        'APP_DIRS': False, # we have no apps
    },
])

import django
django.setup()

然后,您可以像通常一样从字符串加载模板:

from django import template   
t = template.Template('My name is {{ name }}.')   
c = template.Context({'name': 'Rob'})   
t.render(c)

而且,如果您在磁盘中的.configure中写入了DIRS变量,则:

from django.template.loader import get_template
t = get_template('a.html')
t.render({'name': 5})

Django错误:未配置DjangoTemplates后端

http://django.readthedocs.io/zh-CN/latest/releases/1.7.html#standalone-scripts

An addition to what other wrote, if you want to use Django Template on Django > 1.7, you must give your settings.configure(…) call the TEMPLATES variable and call django.setup() like this :

from django.conf import settings

settings.configure(TEMPLATES=[
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['.'], # if you want the templates from a file
        'APP_DIRS': False, # we have no apps
    },
])

import django
django.setup()

Then you can load your template like normally, from a string :

from django import template   
t = template.Template('My name is {{ name }}.')   
c = template.Context({'name': 'Rob'})   
t.render(c)

And if you wrote the DIRS variable in the .configure, from the disk :

from django.template.loader import get_template
t = get_template('a.html')
t.render({'name': 5})

Django Error: No DjangoTemplates backend is configured

http://django.readthedocs.io/en/latest/releases/1.7.html#standalone-scripts


回答 6

我也会说Jinja。它绝对比Django Templating Engine 更强大,并且是独立的

如果这是现有Django应用程序的外部插件,则可以创建一个自定义命令,并在项目环境中使用模板引擎。像这样;

manage.py generatereports --format=html

但是我认为仅仅使用Django模板引擎而不是Jinja是不值得的。

I would say Jinja as well. It is definitely more powerful than Django Templating Engine and it is stand alone.

If this was an external plug to an existing Django application, you could create a custom command and use the templating engine within your projects environment. Like this;

manage.py generatereports --format=html

But I don’t think it is worth just using the Django Templating Engine instead of Jinja.


回答 7

谢谢大家的帮助。这是另外一个。您需要使用自定义模板标签的情况。

假设您在read.py模块中有这个重要的模板标签

from django import template

register = template.Library()

@register.filter(name='bracewrap')
def bracewrap(value):
    return "{" + value + "}"

这是html模板文件“ temp.html”:

{{var|bracewrap}}

最后,这是一个将所有内容捆绑在一起的Python脚本

import django
from django.conf import settings
from django.template import Template, Context
import os

#load your tags
from django.template.loader import get_template
django.template.base.add_to_builtins("read")

# You need to configure Django a bit
settings.configure(
    TEMPLATE_DIRS=(os.path.dirname(os.path.realpath(__file__)), ),
)

#or it could be in python
#t = Template('My name is {{ my_name }}.')
c = Context({'var': 'stackoverflow.com rox'})

template = get_template("temp.html")
# Prepare context ....
print template.render(c)

输出将是

{stackoverflow.com rox}

Thanks for the help folks. Here is one more addition. The case where you need to use custom template tags.

Let’s say you have this important template tag in the module read.py

from django import template

register = template.Library()

@register.filter(name='bracewrap')
def bracewrap(value):
    return "{" + value + "}"

This is the html template file “temp.html”:

{{var|bracewrap}}

Finally, here is a Python script that will tie to all together

import django
from django.conf import settings
from django.template import Template, Context
import os

#load your tags
from django.template.loader import get_template
django.template.base.add_to_builtins("read")

# You need to configure Django a bit
settings.configure(
    TEMPLATE_DIRS=(os.path.dirname(os.path.realpath(__file__)), ),
)

#or it could be in python
#t = Template('My name is {{ my_name }}.')
c = Context({'var': 'stackoverflow.com rox'})

template = get_template("temp.html")
# Prepare context ....
print template.render(c)

The output would be

{stackoverflow.com rox}

回答 8


回答 9

别。改用StringTemplate-一旦知道它,就没有理由考虑其他模板引擎了。

Don’t. Use StringTemplate instead–there is no reason to consider any other template engine once you know about it.


回答 10

我回应以上陈述。Jinja 2是通用模板的一个很好的Django模板超集。我认为他们正在努力使Django模板与settings.py的耦合度降低一些,但是Jinja应该为您做的更好。

I echo the above statements. Jinja 2 is a pretty good superset of Django templates for general use. I think they’re working on making the Django templates a little less coupled to the settings.py, but Jinja should do well for you.


回答 11

运行manage.py外壳程序时:

>>> from django import template   
>>> t = template.Template('My name is {{ me }}.')   
>>> c = template.Context({'me': 'ShuJi'})   
>>> t.render(c)

While running the manage.py shell:

>>> from django import template   
>>> t = template.Template('My name is {{ me }}.')   
>>> c = template.Context({'me': 'ShuJi'})   
>>> t.render(c)

回答 12

Google AppEngine使用Django模板引擎,您是否看过它们的工作方式?您可以使用它。

Google AppEngine uses the Django templating engine, have you taken a look at how they do it? You could possibly just use that.


Django模板如何使用变量查找字典值

问题:Django模板如何使用变量查找字典值

mydict = {"key1":"value1", "key2":"value2"}

查找在Django模板字典值的常规方法是{{ mydict.key1 }}{{ mydict.key2 }}。如果键是循环变量怎么办?即:

{% for item in list %} # where item has an attribute NAME
  {{ mydict.item.NAME }} # I want to look up mydict[item.NAME]
{% endfor %}

mydict.item.NAME失败。如何解决?

mydict = {"key1":"value1", "key2":"value2"}

The regular way to lookup a dictionary value in a Django template is {{ mydict.key1 }}, {{ mydict.key2 }}. What if the key is a loop variable? ie:

{% for item in list %} # where item has an attribute NAME
  {{ mydict.item.NAME }} # I want to look up mydict[item.NAME]
{% endfor %}

mydict.item.NAME fails. How to fix this?


回答 0

编写自定义模板过滤器:

from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

(我.get这样使用,如果不存在该键,则不返回任何键。如果执行dictionary[key]此操作,则将引发一个KeyErrorthen。)

用法:

{{ mydict|get_item:item.NAME }}

Write a custom template filter:

from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

(I use .get so that if the key is absent, it returns none. If you do dictionary[key] it will raise a KeyError then.)

usage:

{{ mydict|get_item:item.NAME }}

回答 1

从循环中的字典中获取键和值:

{% for key, value in mydict.items %}
    {{ value }}
{% endfor %}

我发现这更容易阅读,并且不需要特殊的编码。无论如何,我通常都需要循环内的键和值。

Fetch both the key and the value from the dictionary in the loop:

{% for key, value in mydict.items %}
    {{ value }}
{% endfor %}

I find this easier to read and it avoids the need for special coding. I usually need the key and the value inside the loop anyway.


回答 2

默认情况下不能。点是属性查找/键查找/切片的分隔符/触发器。

点在模板渲染中具有特殊含义。变量名称中的点表示查找。具体来说,当模板系统遇到变量名称中的点时,它将按以下顺序尝试以下查找:

  • 字典查找。示例:foo [“ bar”]
  • 属性查询。示例:foo.bar
  • 列表索引查找。示例:foo [bar]

但是您可以创建一个过滤器,以便您传递参数:

https://docs.djangoproject.com/zh-CN/dev/howto/custom-template-tags/#writing-custom-template-filters

@register.filter(name='lookup')
def lookup(value, arg):
    return value[arg]

{{ mydict|lookup:item.name }}

You can’t by default. The dot is the separator / trigger for attribute lookup / key lookup / slice.

Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

  • Dictionary lookup. Example: foo[“bar”]
  • Attribute lookup. Example: foo.bar
  • List-index lookup. Example: foo[bar]

But you can make a filter which lets you pass in an argument:

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

@register.filter(name='lookup')
def lookup(value, arg):
    return value[arg]

{{ mydict|lookup:item.name }}

回答 3

对我来说template_filters.py,用下面的内容在我的应用程序中创建一个名为python的文件就可以了

# coding=utf-8
from django.template.base import Library

register = Library()


@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

用法就像culebrón所说的:

{{ mydict|get_item:item.NAME }}

For me creating a python file named template_filters.py in my App with below content did the job

# coding=utf-8
from django.template.base import Library

register = Library()


@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

usage is like what culebrón said :

{{ mydict|get_item:item.NAME }}

回答 4

我也有类似的情况。但是我使用了不同的解决方案。

在我的模型中,我创建一个执行字典查找的属性。然后在模板中使用该属性。

在我的模型中:-

@property
def state_(self):
    """ Return the text of the state rather than an integer """
    return self.STATE[self.state]

在我的模板中:-

The state is: {{ item.state_ }}

I had a similar situation. However I used a different solution.

In my model I create a property that does the dictionary lookup. In the template I then use the property.

In my model: –

@property
def state_(self):
    """ Return the text of the state rather than an integer """
    return self.STATE[self.state]

In my template: –

The state is: {{ item.state_ }}

回答 5

因为我不能评论,让我做这一个答案的形式:
建立在culebrón的答案虞姬“富田”富田的答案,传递给函数的字典是一个字符串的形式,因此,也许使用AST。 literal_eval,首先将字符串转换为字典,如本例所示

通过此编辑,代码应如下所示:

@register.filter(name='lookup')
def lookup(value, arg):
    dictionary = ast.literal_eval(value)
    return value.get(arg)

{{ mydict|lookup:item.name }}

Since I can’t comment, let me do this in the form of an answer:
to build on culebrón’s answer or Yuji ‘Tomita’ Tomita’s answer, the dictionary passed into the function is in the form of a string, so perhaps use ast.literal_eval to convert the string to a dictionary first, like in this example.

With this edit, the code should look like this:

# code for custom template tag
@register.filter(name='lookup')
def lookup(value, arg):
    value_dict = ast.literal_eval(value)
    return value_dict.get(arg)

<!--template tag (in the template)-->
{{ mydict|lookup:item.name }}

回答 6

环境:Django 2.2

  1. 示例代码:


    from django.template.defaulttags import register

    @register.filter(name='lookup')
    def lookup(value, arg):
        return value.get(arg)

我将此代码放在名为Portfoliomgr的项目文件夹中的一个名为template_filters.py的文件中

  1. 无论您将过滤器代码放在何处,都要确保该文件夹中有__init__.py

  2. 将该文件添加到projectfolder / settings.py文件中模板部分的库部分。对我来说,它是Portfoliomgr / settings.py



    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
                'libraries':{
                    'template_filters': 'portfoliomgr.template_filters',
                }
            },
        },
    ]
  1. 在您的html代码中加载库

    
    {% load template_filters %}

Environment: Django 2.2

  1. Example code:


    from django.template.defaulttags import register

    @register.filter(name='lookup')
    def lookup(value, arg):
        return value.get(arg)

I put this code in a file named template_filters.py in my project folder named portfoliomgr

  1. No matter where you put your filter code, make sure you have __init__.py in that folder

  2. Add that file to libraries section in templates section in your projectfolder/settings.py file. For me, it is portfoliomgr/settings.py



    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
                'libraries':{
                    'template_filters': 'portfoliomgr.template_filters',
                }
            },
        },
    ]

  1. In your html code load the library

    
    {% load template_filters %}
    

回答 7

环保:django 2.1.7

视图:

dict_objs[query_obj.id] = {'obj': query_obj, 'tag': str_tag}
return render(request, 'obj.html', {'dict_objs': dict_objs})

模板:

{% for obj_id,dict_obj in dict_objs.items %}
<td>{{ dict_obj.obj.obj_name }}</td>
<td style="display:none">{{ obj_id }}</td>
<td>{{ forloop.counter }}</td>
<td>{{ dict_obj.obj.update_timestamp|date:"Y-m-d H:i:s"}}</td>

env: django 2.1.7

view:

dict_objs[query_obj.id] = {'obj': query_obj, 'tag': str_tag}
return render(request, 'obj.html', {'dict_objs': dict_objs})

template:

{% for obj_id,dict_obj in dict_objs.items %}
<td>{{ dict_obj.obj.obj_name }}</td>
<td style="display:none">{{ obj_id }}</td>
<td>{{ forloop.counter }}</td>
<td>{{ dict_obj.obj.update_timestamp|date:"Y-m-d H:i:s"}}</td>

在Jinja中设置变量

问题:在Jinja中设置变量

我想知道如何在Jinja中使用另一个变量设置变量。我会解释,我有一个子菜单,我想显示哪个链接处于活动状态。我尝试了这个:

{% set active_link = {{recordtype}} -%}

其中recordtype是为我的模板提供的变量。

I would like to know how can I set a variable with another variable in jinja. I will explain, I have got a submenu and I would like show which link is active. I tried this:

{% set active_link = {{recordtype}} -%}

where recordtype is a variable given for my template.


回答 0

{{ }}告诉模板打印值,这在您尝试执行的表达式中将不起作用。而是使用{% set %}template标记,然后以与普通python代码相同的方式分配值。

{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}

结果:

it worked

{{ }} tells the template to print the value, this won’t work in expressions like you’re trying to do. Instead, use the {% set %} template tag and then assign the value the same way you would in normal python code.

{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}

Result:

it worked

回答 1

多个变量分配的不错简写

{% set label_cls, field_cls = "col-md-7", "col-md-3" %}

Nice shorthand for Multiple variable assignments

{% set label_cls, field_cls = "col-md-7", "col-md-3" %}

回答 2

像这样设置

{% set active_link = recordtype -%}

Just Set it up like this

{% set active_link = recordtype -%}

Jinja-一个非常快速且富有表现力的模板引擎

Jinja是一个快速、富有表现力、可扩展的模板引擎。模板中的特殊占位符允许编写类似于Python语法的代码。然后向模板传递数据以呈现最终文档

它包括:

  • 模板继承和包含
  • 在模板中定义和导入宏
  • HTML模板可以使用自动转义来防止XSS不受信任的用户输入
  • 沙盒环境可以安全地呈现不受信任的模板
  • AsyncIO支持生成模板和调用异步函数
  • 巴别塔支持I18N
  • 模板可实时编译为优化的Python代码并进行缓存,也可以提前编译
  • 异常指向模板中的正确行,以简化调试
  • 可扩展的过滤器、测试、函数,甚至语法

金佳的理念是,尽管应用程序逻辑可能属于Python,但它不应该因为过多地限制功能而使模板设计人员的工作变得困难

正在安装

安装和更新使用pip

$ pip install -U Jinja2

一言以蔽之

{% extends "base.html" %}
{% block title %}Members{% endblock %}
{% block content %}
  <ul>
  {% for user in users %}
    <li><a href="{{ user.url }}">{{ user.username }}</a></li>
  {% endfor %}
  </ul>
{% endblock %}

捐赠

托盘组织开发并支持金佳和其他受欢迎的套餐。为了扩大贡献者和用户的社区,并允许维护人员将更多的时间投入到项目中,please
donate today

链接

Django-为有最后期限的完美主义者准备的Web框架

Django是一个高级Python Web框架,它鼓励快速开发和干净、实用的设计。感谢您的查看

所有文档都在“docs”目录中,并在线访问https://docs.djangoproject.com/en/stable/.如果您刚刚开始,以下是我们建议您阅读文档的方法:

  • 首先,阅读docs/info/install.txt以获得有关安装Django的说明
  • 接下来,按顺序学习教程(docs/info/tutorial01.txt、docs/info/tutorial02.txt等)。
  • 如果要设置实际的部署服务器,请阅读docs/HOWTO/Deployment/index.txt以获取说明
  • 接下来,您可能想要通读主题指南(在文档/主题中);从那里您可以跳到HOWTO(在文档/HOWTO中)以了解特定问题,并查看参考资料(Docs/ref)以了解血淋淋的详细信息
  • 有关构建文档的HTML版本的说明,请参见docs/readme

文档会严格更新。如果您在文档中发现任何问题,或者认为应该以任何方式加以澄清,请在这里花30秒填写一张罚单:https://code.djangoproject.com/newticket

要获得更多帮助,请执行以下操作:

  • 加入irc.Libera.chat上的#Django频道。那里有很多乐于助人的人。如果您刚接触irc,请访问https://web.libera.chat。
  • 加入Django-Users邮件列表,或在https://groups.google.com/group/django-users上阅读存档

要对Django做出贡献,请执行以下操作:

  • Check out https://docs.djangoproject.com/en/dev/internals/contributing/ for
    information about getting involved.

要运行Django的测试套件,请执行以下操作:

  • Follow the instructions in the “Unit tests” section of
    docs/internals/contributing/writing-code/unit-tests.txt, published online at
    https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/#running-the-unit-tests

Supporting the Development of Django

Django 的发展有赖于你们的贡献。

如果您依赖Django,请记住支持Django软件基金会:https://www.djangoproject.com/fundraising/