【问题标题】:def function in python in a tpl file?tpl文件中python中的def函数?
【发布时间】:2014-02-25 00:33:50
【问题描述】:

你能在模板文件中定义一个函数吗?如果没有,能否在.tpl文件中导入自定义的python库来调用函数?

这是我要调用的函数:

%def rec_print(obj):
    %if "output" not in rec_print.__dict__: rec_print.output = ""
    %end
    %if isinstance(obj, unicode):
        %rec_print.output += "<li>"+str(obj)+ "</li>"
    %elif isinstance(obj, dict):
        %for k, v in obj.items():
            %rec_print.output += "<li>" +str(k) +"</li><ul>"
            %rec_print(v)
            %rec_print.output += "</ul>\n"
    %elif isinstance(obj, list):
        %for items in obj:
            %rec_print(items)
    %else:
        %print "uknown type for", obj, type(obj)
    %end
    %return rec_print.output
%end

我使用这个函数在一个瓶子驱动的 webapp 中生成从我的 mongodb 获取的内容。

【问题讨论】:

  • 如果你使用 mako,我想你可以。
  • 这是一个不同的框架吗?我可能最终会改用 django,但我想尽可能多地使用瓶子。
  • 不,它是一种模板语言,我认为您可以将其安装为bottle 框架。
  • 呃……重新开始……好吧,我去看看。你能用 /__main__ 做点什么吗(想法来自 stackoverflow.com/questions/11614116/…)

标签: python mongodb pymongo bottle


【解决方案1】:

模板:快速和 pythonic 的内置模板引擎,支持 mako、jinja2 和 cheetah 模板。

来自瓶子的网站。

您可以使用 Mako,它是一种用于 Python 的模板语言。您可以将它与瓶子一起使用。这是Defs and Blocks的部分。

【讨论】:

  • 那么,要从瓶子的内置模板中切换,我必须在传入时指定文件名和字典变量?
  • @Jeff 那是一个单独的问题,我鼓励您将它作为一个 SO 问题单独提出。同时,你可以接受这个。
猜你喜欢
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多