Lesson 8 常用的模版标签和过滤器

课程地址:点击这里

主要讲的是templates中模板标签的使用。感觉现在可以敏捷学习了。但这个项目一定要做完。这一部分可以参考一下这篇文章:刘江的博客教程--Django模版语言详解。

杨仕航大神的教程更重实践,论讲解还需要补充。所以从别的资料上把基本定义了解一下。

1. 从views.py到模版

先看views.py

# views.py

from django.shortcuts import render_to_response, get_object_or_404
from .models import BlogType, Blog

# Create your views here.
def blog_list(request):
    context = dict()
    context["blogs"] = Blog.objects.all()
    context["blogs_count"] = Blog.objects.all().count()
    return render_to_response("blog_list.html", context)

def blog_detail(request, blog_id):
    context = dict()
    context["blog"] = get_object_or_404(Blog, pk = blog_id)
    return render_to_response("blog_detail.html", context)

def blogs_with_type(request, blogs_w_type):
    context = dict()
    blog_type = get_object_or_404(BlogType, pk = blogs_w_type)
    context["blogs"] = Blog.objects.filter(blog_type = blog_type)
    context["blog_type"] = blog_type
    return render_to_response("blog_with_type.html", context)

每一个views方法都有比较固定的写法。以最后的blogs_with_type为例:

context = dict() # 创建一个名为context的空字典
blog_type = get_object_or_404(BlogType, pk = blogs_w_type)
context["blogs"] = Blogs.objects.filter(blog_type = type_c)
context["blog_type"] = blog_type
return render_to_response("blog_with_type.html", context)
  • 首先,建立一个名为context的空字典
  • 然后为context添加键值对
  • 最后返回render_to_response方法。左边参数是模板网页,右边参数是context字典。

然后再看blog_with_type.html




    
    {{ blog_type.type_name }}


    
    

共有{{ blogs_count }}篇文章

{% for blog in blogs %}

{{ blog.title }}

{% empty %}

暂无博客,敬请期待!

{% endfor %}

这里面就出现了和普通的html页面不一样的东西。

  • {{blog_count}}:双圆括号,名为“变量”。
  • {{ blogs | length }}:过滤器
  • {% for blog in blogs %}:标签

2. 变量

当模版引擎遇到一个变量,它将从上下文context中获取这个变量的值,然后用值替换掉它本身。

这个context即为方法中定义的字典。然后变量值从views.py中找。

3. 过滤器

过滤器看起来是这样的:{{ name | lower }}。使用管道符号(|)来应用过滤器。该过滤器将文本转换成小写。(引用)

{{ blogs | length }}过滤器的意思是统计博客数量。

4. 标签

标签看起来像是这样的: {% tag %}。

本文中的{% for blog in blogs %}标签是for循环标签。

更多的请从官方查询:

  • Link 1
  • Link 2

你可能感兴趣的:(Lesson 8 常用的模版标签和过滤器)