• 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 %}
    
    
  • 相关阅读:
    [背包问题][二进制优化] Jzoj P4224 食物
    [并查集][排序] Jzoj P4223 旅游
    [哈夫曼树][优先队列] Bzoj P4198 荷马史诗
    [hash][差分][虚树] Jzoj P6011 天天爱跑步
    [dp] Jzoj P6012 荷马史诗
    [dp][递归] Jzoj P4211 送你一棵圣诞树
    [数学] Jzoj P3912 超氧化钾
    堆学习笔记(未完待续)(洛谷p1090合并果子)
    [AC自动机]luogu P2444 病毒
    [概率期望][DP]luogu P3830 随机树
  • 原文地址:https://www.cnblogs.com/yoyoketang/p/15573160.html
Copyright © 2020-2023  润新知