zoukankan      html  css  js  c++  java
  • python测试开发django174.模板中include传递参数 上海

    前言

    模板标签语法 {% include %} ,该标签允许在(模板中)包含其它的模板的内容。
    在多个模板中出现相同的代码时,就应该考虑是否要使用 {% include %} 来减少重复。

    include 使用

    如下这一段如果在多个地方会用到

    <form action="" method="post" id="query_form">
      <div class="form-group">
          <label for="Email1">邮箱地址</label>
          <input type="text" class="form-control" id="Email1" name="email" placeholder="Email">
      </div>
      <div class="form-group">
          <label for="Password1">密码</label>
          <input type="password" class="form-control" id="Password1" name="password"  placeholder="Password">
      </div>
    
      <input type="button"  id="save" class="btn btn-info" value="提交">
    </form>
    

    于是可以使用模板标签语法 {% include %}

    <body>
    
    {% include 'form.html' %}
    
    </body>
    

    templates目录可以新建一个includes目录,专门放需要导入的代码段,层级结构如下

    <body>
    
    {% include 'includes/form.html' %}
    
    </body>
    

    加载的模板名还可以在 view 层中定义, 下面的例子包含了以变量 template_name 的值为名称的模板内容:

    {% include template_name %}
    
    

    include with 使用

    一个网页多次引入同一个子模版,子模板中有些是变量,可以用include with传递变量
    如下form,我们希望id是可变的,每次引入传不同的id值 {{ form_id }}

    <form action="" method="post" id="{{ form_id }}">
      <div class="form-group">
          <label for="Email1">邮箱地址</label>
          <input type="text" class="form-control" id="Email1" name="email" placeholder="Email">
      </div>
      <div class="form-group">
          <label for="Password1">密码</label>
          <input type="password" class="form-control" id="Password1" name="password"  placeholder="Password">
      </div>
    
      <input type="button"  id="save" class="btn btn-info" value="提交">
    </form>
    

    with给变量赋值

    <body>
    
    {% include 'includes/form.html' with form_id='login_form' %}
    
    </body>
    

    传递多个变量

    <form action="" method="{{ method }}" id="{{ form_id }}">
        ......
    </form>
    

    多个变量用空格隔开

    <body>
    
    {% include 'includes/form.html' with form_id='login_form'  method='post'  %}
    
    </body>
    

    默认情况下子模版可以访问父模板的所有变量,在 Django 中还可以通过使用 only 选项来阻止这个默认行为

    {% include 'includes/form.html' with form_id='login_form'  method='post' only %}
    

    with 标签

    另外 Django 还提供了单独的 with 标签来修改或者指定变量的值。
    可以单独使用,也可以搭配 include 标签使用。使用方法如下:

    <!-- 使用 with 标签指定变量 -->
    
    {% with form_id='login_form'  method='post' %}
        {% include 'includes/form.html' %}
    {% endwith %}
    
    
  • 相关阅读:
    ehcache 的 配置文件: ehcache.xml的认识
    Hibernate的二级缓存(SessionFaction的外置缓存)-----Helloword
    QBC检索和本地SQL检索
    HQL的检索方式
    HQL的第一个程序
    Ubuntu Error: No module named 'apt_pkg' 怎么办?
    Linux 后台运行python .sh等程序,以及查看和关闭后台运行程序操作
    ubuntu install redis/mongo 以及 监控安装
    Mac 上的 redis
    Mac 解决硬盘插入不能写的问题
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/15573160.html
Copyright © 2011-2022 走看看