zoukankan      html  css  js  c++  java
  • 02模板渲染和参数(补充:URL传参到视图)

    先抛出代码:

    @app.route('/')
    def index():
        return render_template('index.html',username ="郑勇")

    问题:形如“username”的参数过多会影响维护,解决方案?

    用字典的形式写就好。

    @app.route('/')
    def index():
        content = {
            'username': "郑勇",
            'gender': "",
            'age': "24"
        }
        return render_template('index.html',**content) #注意这里是**号,这里把这个content字典一个个填充进去

    当然还有第二种方式

    @app.route('/')
    def index():
        class Person(object):
            name = "啧啧"
            age = "18"
    
        p = Person()
        content = {
            'username': "哈哈",
            'gender': "",
            'age': "20",
            'person' : p   #这里千万别忘了
        }
        return render_template('index.html',**content)

    此时index文件这样写:

    <p>user:{{ person.name }}</p>  #person对应
    <P>age :{{ person.age }}</P>

    第三种方法,字典中的字典:

    @app.route('/')
    def index():
        class Person(object):
            name = "啧啧"
            age = "18"
    
        p = Person()
        content = {
            'username': "哈哈",
            'gender': "",
            'age': "20",
            'person' : p,
            'websites' :{
                "baidu" : "www.baidu.com",
                "taobao" : "www.taobao.com",
            }
        }
        return render_template('index.html',**content)

    index文件同理:

    <p>user:{{ person.name }}</p>
    <P>age :{{ person.age }}</P>
    <hr>
    <p>网址:{{ websites.baidu }}</p>

     补充:URL传参到视图

  • 相关阅读:
    Python 虚拟环境 virtualenv
    Python
    开发语言之---Java
    LINUX系统
    关系型数据库之MySQL
    开发语言之---Python
    框架之---Django
    递归/面向过程编程
    迭代器/生成器函数及协程函数的编写和使用
    装饰器的编写及使用
  • 原文地址:https://www.cnblogs.com/two-peanuts/p/10538152.html
Copyright © 2011-2022 走看看