zoukankan      html  css  js  c++  java
  • django中将views.py中的python方法传递给html模板文件

    常规的模板渲染

    from django.db import models
    
    # Create your models here.
    
    class ArticalType(models.Model):
        caption = models.CharField(max_length=16)
    
    class Category(models.Model):
        caption = models.CharField(max_length=16)
    
    class Artical(models.Model):
        title = models.CharField(max_length=32)
        content = models.CharField(max_length=255)
    
        category = models.ForeignKey(Category, on_delete=models.CASCADE)
        artical_type = models.ForeignKey(ArticalType, on_delete=models.CASCADE)
    models.py
    urlpatterns = [
        path('admin/', admin.site.urls),
        re_path('artical-(?P<artical_type_id>d+)-(?P<category_id>d+).html', backend.artical),
    ]
    urls.py
    from django.shortcuts import render
    from jax import models
    
    def artical(request, *args, **kwargs):
        print(kwargs)
        artical_type = models.ArticalType.objects.all()
        category = models.Category.objects.all()
        for k,v in kwargs.items():
            if v == '0':
                artical = models.Artical.objects.all()
            else:
                artical = models.Artical.objects.filter(**kwargs)
        return render(request, "artical.html",
                      {"artical_type": artical_type,
                       "category": category,
                       "artical": artical,})
    views.py
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .tag a{
                display: inline-block;
                padding: 3px 5px;
                border: 1px solid #dddddd;
                margin: 5px 5px;
                {#text-decoration: none;#}
            }
            .tag a.w{
                background: #2459a2;
            }
        </style>
    </head>
    <body>
        <h1>搜索条件</h1>
        <div class="tag">
            <div>
                {% if artical_list.artical_type_id == 0 %}
                    <a class="w" href="/artical-0-{{ artical_list.category_id }}.html">全部</a>
                {% else %}
                    <a href="/artical-0-{{ artical_list.category_id }}.html">全部</a>
                {% endif %}
                {% for row in artical_type %}
                    {% if row.id == artical_list.artical_type_id %}
                        <a class="w" href="/artical-{{ row.id }}-{{ artical_list.category_id }}.html">{{ row.caption }}</a>
                    {% else %}
                        <a href="/artical-{{ row.id }}-{{ artical_list.category_id }}.html">{{ row.caption }}</a>
                    {% endif %}
                {% endfor %}
            </div>
            <div>
                {% if artical_list.category_id == 0 %}
                    <a class="w" href="/artical-{{ artical_list.artical_type_id }}-0.html">全部</a>
                {% else %}
                    <a href="/artical-{{ artical_list.artical_type_id }}-0.html">全部</a>
                {% endif %}
                {% for row in category %}
                    {% if row.id == artical_list.category_id %}
                        <a class="w" href="/artical-{{ artical_list.artical_type_id }}-{{ row.id }}}}.html">{{ row.caption }}</a>
                    {% else %}
                        <a href="/artical-{{ artical_list.artical_type_id }}-{{ row.id }}.html">{{ row.caption }}</a>
                    {% endif %}
                {% endfor %}
            </div>
        </div>
        <h1>搜索结果</h1>
        <ul>
            {% for row in artical %}
                <li>{{ row.id }} - {{ row.title }}</li>
            {% endfor %}
        </ul>
    
    </body>
    </html>
    artical.html

    将views.py中的python方法传递给html模板文件:

    from django.shortcuts import render
    from jax import models
    
    def artical(request, *args, **kwargs):
        print(kwargs)
        artical_type = models.ArticalType.objects.all()
        category = models.Category.objects.all()
        for k,v in kwargs.items():
            kwargs[k] = int(v)    # 新添加
            if v == '0':
                artical = models.Artical.objects.all()
            else:
                artical = models.Artical.objects.filter(**kwargs)
        return render(request, "artical.html",
                      {"artical_type": artical_type,
                       "category": category,
                       "artical": artical,
                       'artical_list': kwargs})    # 新添加
    views.py

    在app下新建目录templatetags(必须为这个名字),里面可以自定义文件名称,这里定义为filter.py

    from django import template
    from django.utils.safestring import mark_safe
    register = template.Library()
    
    @register.simple_tag
    def filter_all(artical_list, k):
        '''
        {% if artical_list.artical_type_id == 0 %}
            <a class="w" href="/artical-0-{{ artical_list.category_id }}.html">全部</a>
        {% else %}
            <a href="/artical-0-{{ artical_list.category_id }}.html">全部</a>
        {% endif %}
        :return:
        '''
        if k == "artical_type_id":
            n1 = artical_list["artical_type_id"]
            n2 = artical_list["category_id"]
            if n1 == 0:
                ret = '<a class="w" href="/artical-0-%s.html">全部</a>' % n1
            else:
                ret = '<a href="/artical-0-%s.html">全部</a>' % n2
        else:
            n1 = artical_list["category_id"]
            n2 = artical_list["artical_type_id"]
            if n1 == 0:
                ret = '<a class="w" href="/artical-%s-0.html">全部</a>' % n2
            else:
                ret = '<a href="/artical-%s-0.html">全部</a>' % n2
        return mark_safe(ret)
    
    @register.simple_tag
    def filter_artical_type(artical_type, artical_list):
        """
        {% for row in artical_type %}
            {% if row.id == artical_list.artical_type_id %}
                <a class="w" href="/artical-{{ row.id }}-{{ artical_list.category_id }}.html">{{ row.caption }}</a>
            {% else %}
                <a href="/artical-{{ row.id }}-{{ artical_list.category_id }}.html">{{ row.caption }}</a>
            {% endif %}
        {% endfor %}
        :return:
        """
        ret = []
        for row in artical_type:
            if row.id == artical_list["artical_type_id"]:
                temp = '<a class="w" href="/artical-%s-%s.html">%s</a>' % (row.id, artical_list["category_id"],row.caption)
            else:
                temp = '<a href="/artical-%s-%s.html">%s</a>' % (row.id, artical_list["category_id"], row.caption)
            ret.append(temp)
        return mark_safe(''.join(ret))
    
    @register.simple_tag
    def filter_category(category, artical_list):
        """
        {% for row in category %}
            {% if row.id == artical_list.category_id %}
                <a class="w" href="/artical-{{ artical_list.artical_type_id }}-{{ row.id }}}}.html">{{ row.caption }}</a>
            {% else %}
                <a href="/artical-{{ artical_list.artical_type_id }}-{{ row.id }}.html">{{ row.caption }}</a>
            {% endif %}
        {% endfor %}
        :param category:
        :param artical_list:
        :return:
        """
        ret = []
        for row in category:
            if row.id == artical_list["category_id"]:
                temp = '<a class="w" href="/artical-%s-%s.html">%s</a>' % (artical_list["artical_type_id"], row.id, row.caption)
            else:
                temp = '<a href="/artical-%s-%s.html">%s</a>' % (artical_list["artical_type_id"], row.id, row.caption)
            ret.append(temp)
        return mark_safe(''.join(ret))
    filter.py

    前端html文件倒入方法,以及传递参数

    {% load filter %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .tag a{
                display: inline-block;
                padding: 3px 5px;
                border: 1px solid #dddddd;
                margin: 5px 5px;
                {#text-decoration: none;#}
            }
            .tag a.w{
                background: #2459a2;
            }
        </style>
    </head>
    <body>
        <h1>搜索条件</h1>
        <div class="tag">
            <div>
                {% filter_all artical_list 'artical_type_id' %}
    {#            {% if artical_list.artical_type_id == 0 %}#}
    {#                <a class="w" href="/artical-0-{{ artical_list.category_id }}.html">全部</a>#}
    {#            {% else %}#}
    {#                <a href="/artical-0-{{ artical_list.category_id }}.html">全部</a>#}
    {#            {% endif %}#}
                {% filter_artical_type artical_type artical_list %}
    {#            {% for row in artical_type %}#}
    {#                {% if row.id == artical_list.artical_type_id %}#}
    {#                    <a class="w" href="/artical-{{ row.id }}-{{ artical_list.category_id }}.html">{{ row.caption }}</a>#}
    {#                {% else %}#}
    {#                    <a href="/artical-{{ row.id }}-{{ artical_list.category_id }}.html">{{ row.caption }}</a>#}
    {#                {% endif %}#}
    {#            {% endfor %}#}
            </div>
            <div>
                {% filter_all artical_list 'category_id' %}
    {#            {% if artical_list.category_id == 0 %}#}
    {#                <a class="w" href="/artical-{{ artical_list.artical_type_id }}-0.html">全部</a>#}
    {#            {% else %}#}
    {#                <a href="/artical-{{ artical_list.artical_type_id }}-0.html">全部</a>#}
    {#            {% endif %}#}
                {% filter_category category artical_list %}
    {#            {% for row in category %}#}
    {#                {% if row.id == artical_list.category_id %}#}
    {#                    <a class="w" href="/artical-{{ artical_list.artical_type_id }}-{{ row.id }}}}.html">{{ row.caption }}</a>#}
    {#                {% else %}#}
    {#                    <a href="/artical-{{ artical_list.artical_type_id }}-{{ row.id }}.html">{{ row.caption }}</a>#}
    {#                {% endif %}#}
    {#            {% endfor %}#}
            </div>
        </div>
        <h1>搜索结果</h1>
        <ul>
            {% for row in artical %}
                <li>{{ row.id }} - {{ row.title }}</li>
            {% endfor %}
        </ul>
    
    </body>
    </html>
    artical.html

    转换时需要注意:

    1.在app下新建的目录名字必须为templatetags。

    2.html文件第一行需要添加"{% load 文件名 %}",以此来倒入自定义前端方法中的函数。

    3.新建的函数文件中需要倒入模块

    from django import template
    from django.utils.safestring import mark_safe
    register = template.Library()

    以及需要对自定义方法添加装饰器
    @register.simple_tag
    def fun(*args, **kwargs):
    pass

     方法二:

    在templatetags目录中新建py文件,这里的"blog_left_menu.html"是另一个html模板文件

    from jax import models
    from django import template
    
    
    register = template.Library()
    
    @register.inclusion_tag("blog_left_menu.html")
    def function():
        ...

    # 这里function()里面处理后数据返回仍然需要以字典形式返回给"blog_left_menu.html",直接用return返回字典即可,不需要render。

    其他模板引用方法:

    {% load blog_left_menu %}   <!--导入templatetags目录当中的文件-->
    
    {% get_left_menu username %}    <!--引用所倒入文件blog_left_menu.py中的get_left_menu方法,并且提供username作为参数}-->

    方法一是正常的将前端代码转换为py方法。

    方法二更像是通过一次请求对模板做两次的渲染。

  • 相关阅读:
    连接池的配置与维护
    对面向对象的理解
    ActiveMQ重试机制
    activemq持久化的几种方式详解
    zookeeper写数据流程
    G1垃圾回收器
    REDIS哨兵模式和集群模式
    REDIS复制
    REDIS参数配置和运行状态
    slow-log 和bin-log相关参数介绍
  • 原文地址:https://www.cnblogs.com/ttyypjt/p/10382001.html
Copyright © 2011-2022 走看看