Django关于标签(tag)

1.if
使用语法如下:

{% if name == 'yuan' and hobby|length < 5 %}
        hello yuan
{% elif name == 'fuck' %}
        hello shit
{% else %}
        no user
{% endif %}

注意:1). if中不允许使用括号,如果想表示优先级,使用if嵌套;
2). if中可使用filter;
3). 可使用 ==, !=, <, >, <=, >=, in, not in, is, is not 等操作符;

2.for
使用方法如下:

{% for x in hobby %}
        <h1>{{ forloop.counter }}:{{ x|add:'ha' }}</h1>

{% endfor %}
#result
1:musicha
2:paintha
3:fuckha

注意:1) for循环内可使用如下几种变量来获得循环的索引值: forloop.counter, forloop.counter0, forloop.revcounter, forloop.revcounter0
2)也可对字典进行如下遍历:

{% for key, value in data.items %}
 {{ key }}: {{ value }} 
 {% endfor %}

Keep in mind that for the dot operator, dictionary key lookup takes precedence over method lookup. Therefore if the data dictionary contains a key named ‘items’, data.items will return data[‘items’] instead of data. items(). Avoid adding keys that are named like dictionary methods if you want to use those methods in a template (items, values, keys, etc.). Read more about the lookup order of the dot operator in the documentation of template variables

如果字典的键和item方法, value方法等重名, 会优先调取字典的键, 所以键命名时应尽量避免上述行为;
3) for循环中还可添加empty标签,在循环的对象为空时调用,使用方法如下:

{% for x in hobby %}
        <h1>{{ forloop.counter }}:{{ x|add:'ha' }}</h1>
        <h1>{{ forloop.revcounter0 }}:{{ x|add:'ppp' }}</h1>
{% empty %}
        <h1>空的!</h1>
{% endfor %}

3.csrf_token

This tag is used for CSRF protection, as described in the documentation for Cross Site Request Forgeries.

用于CSRF保护,写在当form表单提交方式为post时, 须写在form标签中,这样在第一次访问该网页时,就会给浏览器发一把访问的"钥匙",以便后续的表单提交;

4.autoescape

Controls the current auto-escaping behavior. This tag takes either on or off as an argument and that determines whether auto-escaping is in effect inside the block. The block is closed with an endautoescape ending tag. When auto-escaping is in effect, all variable content has HTML escaping applied to it before placing the result into the output (but after any filters have been applied). This is equivalent to manually applying the escape filter to each variable. The only exceptions are variables that are already marked as “safe” from escaping, either by the code that populated the variable, or because it has had the safe or escape filters applied. Sample usage:

{% autoescape on %} 
{{ body }} 
{% endautoescape %}

通过此标签的on或off参数来控制是否对内部的代码进行转义, 而具有safe过滤器的变量则不受影响,如:

{% autoescape on %}
        {{ a|safe }}  # a="<h1>hello</h1>"
{% endautoescape %}
#result
hello

5.filter

Filters the contents of the block through one or more filters. Multiple filters can be specified with pipes and filters can have arguments, just as in variable syntax. Note that the block includes all the text between the filter and endfilter tags. Sample usage:

{% filter force_escape|lower %} 
This text will be HTML-escaped, and will appear in all lowercase. 
{% endfilter %}

Note: The escape and safe filters are not acceptable arguments. Instead, use the autoescape tag to manage autoescaping for blocks of template code.

`通过此标签可以调用多个过滤器,但要注意escape和safe过滤器不可用;
例如:

{% filter upper|add:'shit' %}
        {{ name }}  # name=yuan liuy yha
    {% endfilter %}
#result
YUAN LIUY YHA shit

6.ifchanged

Check if a value has changed from the last iteration of a loop. The {% ifchanged %} block tag is used within a loop. It has two possible uses. 1. Checks its own rendered contents against its previous state and only displays the content if it has changed. For example, this displays a list of days, only displaying the month if it changes:

<h1>Archive for {{ year }}</h1>
{% for date in days %} 
{% ifchanged %}
<h3>{{ date|date:"F" }}</h3>
{% endifchanged %} 
<a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a> 
{% endfor %}

用在循环中,判断和上次循环相比是否改变;

7.load

Loads a custom template tag set. For example, the following template would load all the tags and filters registered in somelibrary and otherlibrary located in package package:

{% load somelibrary package.otherlibrary %}

可以加载用户自己定制的过滤器或标签库;方式如上;

You can also selectively load individual filters or tags from a library, using the from argument. In this example, the template tags/filters named foo and bar will be loaded from somelibrary:

{% load foo bar from somelibrary %}

See Custom tag and filter libraries for more information.

也可调取其中几个过滤器或标签;

8.now

Displays the current date and/or time, using a format according to the given string. Such string can contain format specifiers characters as described in the date filter section. Example:

It is {% now "jS F Y H:i" %}

Note that you can backslash-escape a format string if you want to use the “raw” value. In this example, both “o” and “f” are backslash-escaped, because otherwise each is a format string that displays the year and the time, respectively:

It is the {% now "jS \o\f F" %}

This would display as “It is the 4th of September”.
Note: The format passed can also be one of the predefined ones DATE_FORMAT, DATETIME_FORMAT, SHORT_DATE_FORMAT or SHORT_DATETIME_FORMAT. The predefined formats may vary depending on the current locale and if Format localization is enabled, e.g.:

It is {% now "SHORT_DATETIME_FORMAT" %}

You can also use the syntax {% now “Y” as current_year %} to store the output (as a string) inside a variable. This is useful if you want to use {% now %} inside a template tag like blocktrans for example:

{% now "Y" as current_year %} 
{% blocktrans %}
Copyright {{ current_year }}
{% endblocktrans %}

表示现在的时间;

9.url

1)Returns an absolute path reference (a URL without the domain name) matching a given view and optional parameters. Any special characters in the resulting path will be encoded using iri_to_uri(). This is a way to output links without violating the DRY principle by having to hard-code URLs in your templates:

{% url 'some-url-name' v1 v2 %}

返回与给出的视图和参数匹配的不带主机名的绝对路径, 如果有特殊字符会用iri_to_uri()进行编码;这是一种可以在不违反DRY原则的情况下在模板中对url硬编码并输出链接的方法;

2)The first argument is a URL pattern name. It can be a quoted literal or any other context variable. Additional arguments are optional and should be space-separated values that will be used as arguments in the URL. The example above shows passing positional arguments. Alternatively you may use keyword syntax:

{% url 'some-url-name' arg1=v1 arg2=v2 %}
<form action="{% url 'art' '2018' '12' %}" method="get" >

第一个参数写URL pattern name, 可以是带引号的文本或任何上下文变量; 其他参数为可选,用空格分割, 它们将用作URL中的参数;当然也可使用关键字参数的形式;

Do not mix both positional and keyword syntax in a single call. All arguments required by the URLconf should be present.

但要注意的是,关键字参数和位置参数不能混用,所有参数都应列出来;

If you’d like to retrieve a URL without displaying it, you can use a slightly different call:

{% url 'some-url-name' arg arg2 as the_url %}
<a href="{{ the_url }}">I'm linking to {{ the_url }}</a>

The scope of the variable created by the as var syntax is the {% block %}in which the {% url %} tag appears. This {% url … as var %} syntax will not cause an error if the view is missing. In practice you’ll use this to link to views that are optional:

{% url 'some-url-name' as the_url %} 
{% if the_url %} 
<a href="{{ the_url }}">Link to optional stuff</a> 
{% endif %}

If you’d like to retrieve a namespaced URL, specify the fully qualified name:
{% url ‘myapp:view-name’ %}
This will follow the normal namespaced URL resolution strategy, including using any hints provided by the context as to the current application.

Warning: Don’t forget to put quotes around the URL pattern name, otherwise the value will be interpreted as a context variable!

url标签也可以使用 as 变量名 的方式来重新临时命名, 方便使用;

10.verbatim

Stops the template engine from rendering the contents of this block tag.
A common use is to allow a JavaScript template layer that collides with Django’s syntax. For example:

{% verbatim %} 
{{if dying}}Still alive.{{/if}} 
{% endverbatim %}

阻止模板渲染该标签中的内容;

11.with

1)Caches a complex variable under a simpler name. This is useful when accessing an “expensive” method (e.g., one that hits the database) multiple times. For example:

{% with total=business.employees.count %} 
{{ total }} employee{{ total|pluralize }} 
{% endwith %}

以更简单的名称缓存复杂的变量名, 这种方法在使用变量多次访问数据库时很有用;

The populated variable (in the example above, total) is only available between the {% with %} and {% endwith %} tags.

当然,这种命名方法只在with标签中生效;

2)You can assign more than one context variable:

{% with alpha=1 beta=2 %} ... {% endwith %}

Note: The previous more verbose format is still supported: {% with business.employees.count as total %}

也可以同时对多个变量命名,支持{% with business.employees.count as total %}的格式;例如:

{% with name as n %}
    {% filter upper|add:'shit' %}
        {{ n }}
    {% endfilter %}
{% endwith %}

12.extends

1)Signals that this template extends a parent template. This tag can be used in two ways:
• {% extends “base.html” %} (with quotes) uses the literal value “base.html” as the name of the parent template to extend.
• {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template. See Template inheritance for more information.

表明该模板将会继承一个父模板, 有两种调用方式. 一种为加引号的字符串,表示父模板的名字; 另一种为变量,如果变量为字符串,那字符串作为父模板的文件名,如果是一个Template对象,那将该对象作为父模板;

2)Normally the template name is relative to the template loader’s roo tdirectory. A string argument may also be a relative path starting with ./ or …/. For example, assume the following directory structure:
dir1/ template.html
base2.html
my/
base3.html
base1.html
In template.html, the following paths would be valid:
{% extends “./base2.html” %}
{% extends “…/base1.html” %}
{% extends “./my/base3.html” %}

通常情况下模板名称目录为模板加载文件目录的相对目录, 例如以上几种方式都是有效的路径调用方式;
调用方式如下:

{% extends "aaa.html" %}

{% block content%}
    {{ block.super }}
    <h1>this is shit {{ name }}</h1>
{% endblock %}

注意:1)extends要写在开头,否则无效;
2)通过block.super变量可以访问父模板的内容;
3)通过block标签来替换父模板中的内容,且block标签不能重名;
4)一般来说block越多越好,因为可扩展性越好;

13.include

1)Loads a template and renders it with the current context. This is a way of “including” other templates within a template. The template name can either be a variable or a hard-coded (quoted) string, in either single or double quotes. This example includes the contents of the template “foo/bar.html”:

{% include "foo/bar.html" %}

加载一个模板并用当前的上下文渲染它; 这是在一个模板中调入另一个模板的方法;模板名可以是一个字符串或变量;

2)Normally the template name is relative to the template loader’s root directory. A string argument may also be a relative path starting with ./ or …/ as described in the extends tag. This example includes the contents of the template whose name is contained in the variable template_name:

{% include template_name %}

The variable may also be any object with a render() method that accepts a context. This allows you to reference a compiled Template in your context.

和extends一样,模板名也是调用者的根目录的相对目录, 变量也可能是具有render()方法的任何对象;这允许你在上下文中引用已编译的模板;

3)The variable may also be any object with a render() method that accepts a context. This allows you to reference a compiled Template in your context. An included template is rendered within the context of the template that includes it. This example produces the output “Hello, John!”:
• Context: variable person is set to “John” and variable greeting is set to “Hello”.
• Template:{% include “name_snippet.html” %}

The name_snippet.html template:
{{ greeting }}, {{ person|default:“friend” }}!

You can pass additional context to the template using keyword arguments:
{% include “name_snippet.html” with person=“Jane” greeting=“Hello” %}

If you want to render the context only with the variables provided (or even no variables at all), use the only option. No other variables are available to the included template:
{% include “name_snippet.html” with greeting=“Hi” only %}

可以利用with 和only在include中传入上下文变量,注意是已关键字参数的形式;

4)Note: The include tag should be considered as an implementation of “render this subtemplate and include the HTML”, not as “parse this subtemplate and include its contents as if it were part of the parent”. This means that there is no shared state between included templates – each include is a completely independent rendering process. Blocks are evaluated before they are included. This means that a template that includes blocks from another will contain blocks that have already been evaluated and rendered - not blocks that can be overridden by, for example, an extending template.

注意:include标记应该被视为“渲染此子模板并包含HTML”的实现,而不是“解析此子模板并将其内容包含在内,就好像它是父节点的一部分”。 这意味着包含的模板之间没有共享状态 - 每个include都是完全独立的渲染过程。 在块在包含之前对块进行评估。 这意味着包含来自另一个块的模板将包含已经评估和渲染的块 - 而不是像extends一样可以被覆盖的块。

{% include "aaa.html" %} #当中包含content1块
{% include "bbb.html" %}
{% block content1 %}
    <h1>this is ccc.html</h1>
{% endblock %}

include的模板间相互独立,与父模板也相互独立,无法在父模板中对其进行任何渲染,只能在view函数中利用render()在开始时进行渲染;

14.自定制filter和simple_tag:
(1)在app中创建templatetags文件夹;
(2)创建任意.py文件,如my_tag;
(3)在.py文件中写代码:

from django import template
from django.utils.safestring import mark_safe

register = template.Library()
@register.filter()
def multi(x, y):
    return x*y


@register.simple_tag()
def multi_tag(x, y, z):
    return x*y*z

#调用
{{ b|multi:4 }}
{% multi_tag b 5 10 %}

(4)在使用的文件中加载:{% load my_tag %};
(5)在settings文件中注册当前app;

注意:1)filter只能传入一个参数, 但可以在if标签中使用; simple_tag相反,传入的参数不限,但不能用在if标签中;

15.其余待补充…

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Django允许开发者自定义标签库,以便在模板中使用自定义的标签和过滤器。下面是一些步骤,用于创建和使用自定义标签库: 1. 首先,在你的Django项目中创建一个名为`templatetags`的目录。这个目录应该位于你的应用程序的根目录下。 2. 在`templatetags`目录中创建一个Python模块文件(例如`my_tags.py`),这个文件将包含你的自定义标签和过滤器。 3. 在`my_tags.py`文件中,导入`django.template.Library`类,并创建一个`register`实例,用于注册你的自定义标签和过滤器。 4. 在`register`实例上使用`simple_tag`装饰器来定义一个简单的标签。你可以在装饰器中指定标签的名称。 ```python from django import template register = template.Library() @register.simple_tag def my_custom_tag(): # 标签的逻辑代码 return "Hello, world!" ``` 5. 如果你想定义一个接收参数的标签,可以使用`assignment_tag`装饰器。这样你可以在模板中使用标签并将结果赋值给一个变量。 ```python @register.assignment_tag def my_custom_tag_with_params(param1, param2): # 标签的逻辑代码 return param1 + param2 ``` 6. 如果你要定义一个过滤器,可以使用`filter`装饰器。 ```python @register.filter def my_custom_filter(value): # 过滤器的逻辑代码 return modified_value ``` 7. 在你的模板中,首先加载自定义标签库,然后就可以使用你定义的标签和过滤器了。 ```django {% load my_tags %} {% my_custom_tag %} {% my_custom_tag_with_params 1 2 as result %} {{ result }} {{ some_value|my_custom_filter }} ``` 这就是使用Django自定义标签库的基本步骤。你可以在`my_tags.py`文件中定义更多的标签和过滤器,以满足你的项目需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值