将变量传递到jinja导入或从父html文件包含 [英] passing a variable into a jinja import or include from a parent html file

查看:49
本文介绍了将变量传递到jinja导入或从父html文件包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景将是:

您有一个名为person的变量,其中包含要传递给部分html的许多字段,例如名称,地址等"-例如,这种解决方案可能是搜索客户的结果

"you have a variable called person which contains a number of fields like name, address, etc which you want to pass to a partial piece of html" - this solution could be results from a search for customers for example

snippet.html

snippet.html

<div id="item">
  <ul>
     <li>
         <span>{{name}}</span>
         <span>{{address}}</span>
     <li>
  </ul>
</div>

mypage.html

mypage.html

<div id="result">
   {% include "snippet.html" passing {{person}} %}
</div>

实现此目标的最佳方法是什么.在文档中,它谈到了到处传递上下文,但是在我看来,渲染模板时,这是一个相当大的对象.当然,将特定对象传递到每个模板中会更容易吗?

What is the best way to achieve this. In the documentation it talks about passing context around everywhere, but that seems to me to be a rather large object when rendering templates. surely it is easier to pass specific objects into each template?

推荐答案

当您将模板包含到另一个模板中时,它就可以访问其上下文,因此,如果将person变量传递给mypage.html的上下文,您将可以从导入的模板访问它,如下所示:

When you include a template into another one, it gains access to its context, so if you pass your person variable to mypage.html's context, you'll be able to access it from your imported template like this:

snippet.html:

<div id="item">
    <ul>
        <li>
            <span>{{ person.name }}</span>
            <span>{{ person.address }}</span>
        </li>
    </ul>
</div>

mypage.html:

<div id="result">
    {% include 'snippet.html' %}
</div>

view.py:

def view(person_id):
    person = Person.get(person_id) # or whatever source you get your data from
    return render_template('mypage.html', person=person)

这篇关于将变量传递到jinja导入或从父html文件包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆