【问题标题】:how to pass own dictionary to sub-template如何将自己的字典传递给子模板
【发布时间】:2016-11-25 14:56:53
【问题描述】:

使用bottlepysimple template engine 我想知道如何将整个传递 到模板的字典传递到它的子模板。

例如在我的main.py 我有:

@bottle.route('/')
@bottle.view('main')
def index():
    """main page"""
    return {"name": "main", "foo": 12, "flag": True}

我想将字典中的所有值从我的main.tpl 传递给sub.tpl

$ cat sub.tpl
<h1>Hello, {{name}}</h1>

$ cat main.tpl
% include('subtemplate', name=name, foo=foo, flag=flag)

枚举每个键(如上例所示)当然不是很可扩展也不是很灵活。

那么:有没有办法传递整个环境?

类似

$ cat main.tpl
% include('subtemplate', *env)

【问题讨论】:

  • 你为什么不直接通过:include('subtemplate', index())?
  • @JossieCalderon 无限递归?
  • @LukasGraf 我不明白怎么做?请?教育?我?
  • @JossieCalderon 调用index() 将再次渲染main 模板,index() 将再次被调用,...除非瓶子/STE 做一些魔术来检测该循环并打破它,我看不出这不会以无限递归结束

标签: python templates template-engine bottle


【解决方案1】:

只是一个想法,从我的脑海中消失。 (即未经测试。)

@bottle.route('/')
@bottle.view('main')
def index():
    """main page"""
    env = {"name": "main", "foo": 12, "flag": True}  # same vars as before
    env["env"] = env  # add a reference to the entire dict, for passing deeper into subtemplates
    return env

然后:

% include('subtemplate', env=env)

编辑

感谢@Kwartz 提出以下改进建议。

更简洁的方法是:

% include('subtemplate', **env)

尚未尝试过,但如果**locals() 有效(感谢@Lukas Graf 尝试并确认),那么期望**env 也可以正常工作是合理的。

【讨论】:

  • 或者,更好的是,% include('subtemplate', **env)
  • @Kwarrtz 确实很好。不确定参数扩展是否适用于 Bottle 模板。你试过了吗?
  • 我用% include('subtemplate', **locals()) 试了一下,似乎奏效了。但这将传递main 的整个范围,这可能会产生意想不到的副作用,所以我更喜欢你构建自己的env 的方法。
  • 谢谢!我将更新答案以包含该事实。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-06
  • 2019-02-15
  • 1970-01-01
相关资源
最近更新 更多