Django笔记(三) 模板和目录等

模板

模板路径

//模板路径设置(新版本使用默认??》一般使用默认,有需求时再去设置)

#一般不用去管这个
import os.path
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)

模板继承

{% extends "base.html" %}

模块化

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

控制流语句

使用dict

{% for k,v in dict.items %}
通过key获取value,可以多级
{{ item.key }}{{ item.key1.key2 }}等价于item[key]item[key1][key2]

if/else

{% if today_is_weekend %}
    <p>Welcome to the weekend!</p>
{% else %}
    <p>Get back to work.</p>
{% endif %}

{%if %}标签接受and,or或者not关键字来对多个变量做判断,或者对变量取反not
没有{{% elif %}}标签,使用嵌套的{% if %}标签来达成同样的效果:

{% if athlete_list %}
    <p>Here are the athletes:{{ athlete_list }}.</p>
{% else %}
    <p> No athletes are available.</p>
    {% if coach_list %}
        <p> Here are the coaches: {{ coach_list }}.</p>
    {% endif %}
{% endif %}

for

{% for %}用于序列迭代。每一次循环中,模板系统会渲染在{% for %}{% endfor %}之间的所有内容。
例:反向迭代 reversed,列表为空时,输出empty分句

{% for a in b reversed %}
...
{% empty %}
...
{% endfor %}

Django不支持退出循环操作,也不支持 continue语句。forloop.counter表示当前循环执行次数的整数计数器,其他计数器forloop.counter0, forloop.revecounter, forloop.revcounter0, forloop.first,forloop.last,forloop.parentloop

{% for object in objects %}
    {% if forloop.first %}<li class="first">{% else %}<li>{% endif %}
    {{ object }}
{% endif %}
{% for link in links %}{{ link }} 
    {% if not forloop.last %}} | {% endif %}
{% endfor %}

Numeric for loop in Django templates

{% for i in "xxxxxxxxxxxxxxxxxxxx" %}
    {{ forloop.counter0 }}
{% endfor %}

另一种似乎更优雅的方法
context['loop_times'] = range(1, 8)

{% for i in loop_times %}
        <option value={{ i }}>{{ i }}</option>
{% endfor %}

内置标签和过滤器

http://python.usyiyi.cn/django/ref/templates/builtins.html

转义

{{value|safe|linkbreaks}}
safe关闭转义(文字转成html代码),linkbreaks或linkbreaksbr把\n转换成br或者br+p

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

filter 多个过滤器对内容过滤

通过一个或多个过滤器对内容过滤,作为灵活可变的语法,多个过滤器被管道符号相连接,且过滤器可以有参数。注意块中所有的内容都应该包括在filter 和endfilter标签中。

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

firstof 输出第一个不为False的参数

{% firstof var1 var2 var3 "fallback value" %}

比较 运算等

http://python.usyiyi.cn/django/ref/templates/builtins.html#ifequal
加减法用add
{{ i|add:'-1' }}
乘除法用widthratio
To compute A*B: {% widthratio A 1 B %}
To compute A/B: {% widthratio A B 1 %}
https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#widthratio

Forms 表单

搜索功能

http://www.djangobook.com/en/2.0/chapter07.html

请求头信息

request.path
request.get_host()
request.get_full_path()
request.META

获取meta信息

# BAD!
def ua_display_bad(request):
    ua = request.META['HTTP_USER_AGENT']  # Might raise KeyError!
    return HttpResponse("Your browser is %s" % ua)

# GOOD (VERSION 1)
def ua_display_good1(request):
    try:
        ua = request.META['HTTP_USER_AGENT']
    except KeyError:
        ua = 'unknown'
    return HttpResponse("Your browser is %s" % ua)

# GOOD (VERSION 2)
def ua_display_good2(request):
    ua = request.META.get('HTTP_USER_AGENT', 'unknown')
    return HttpResponse("Your browser is %s" % ua)

获取当前url

http://stackoverflow.com/questions/2882490/get-the-current-url-within-a-django-template
新版本不需要context_instance=,只需render({request,’xx.html’,{}),render取代了render_to_response
不带参数{{request.path}}
带参数{{request.get_full_path}}

static 目录

http://stackoverflow.com/questions/14799835/django-static-files-results-in-404

# 在nginx和apache配置文件中设置alias感觉更方便,只是使用django自带的服务器测试时会丢失样式,我一般就在nginx中设置了
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATIC_DIR=[
    '/home/project/static',
]
#  nginx 静态文件路径设置,把它加在它该出现的地方 
    location /static {
        alias /path/to/your/mysite/static; # your Django project's static files - amend as required
    }

自定义标签

要在templatetags目录下创建一个__init__.py文件,filter才能生效

    原文作者:今夕何夕_walker
    原文地址: https://www.jianshu.com/p/29458fcb651d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞