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 %}
    
    
  • 相关阅读:
    LOL 战斗力查询
    D3js-对柱状图的增,删,排序
    我的项目7 js 实现歌词同步(额,小小的效果)
    为什么电脑启动任务管理器会这样
    OpenCV求取轮廓线
    leetcode-Reverse Words in a String
    Linux lvs DR配置
    p2p网贷3种运营模式
    T4308 数据结构判断
    1080 线段树练习
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/15573160.html
Copyright © 2011-2022 走看看