如何动态选择要在烧瓶中使用的模板目录? [英] How to dynamically select template directory to be used in flask?

查看:122
本文介绍了如何动态选择要在烧瓶中使用的模板目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  / flaskapp 
/application.py

默认情况下,flask使用存储在template目录下的模板文件:
/ templates
/hello.html

有什么办法可以动态选择模板目录根据用户登录?这是我想要的目录结构:

pre $ fla $
$ app $
$ /模板(默认模板在这里)
/hello.html
/ userdata
/ user1
/ template1
hello.html
/ template2
hello.html
/ user2
/ template1
hello.html
/ template2
hello.html
$ b $现在如果我有登录用户的用户名和用户激活的模板名称,是否可以动态选择目录来加载模板文件?例如,

  / userdata /< username> /<激活模板名称> / 



而不是固定的

  / templates / 

我想要实现的是我的Web应用程序的WordPress主题系统,用户可以上传/选择他的网站的主题。

解决方案

也有可能覆盖Jinja loader并设置Jinja将寻找的路径模板。像:

  my_loader = jinja2.ChoiceLoader([
app.jinja_loader,
jinja2.FileSystemLoader([ '/ flaskapp / userdata',
'/ flaskapp / templates']),
])
app.jinja_loader = my_loader

目录按Jinja需要先查找的顺序排列。然后从视图中,您可以渲染用户特定的模板,如下所示:

  render_template('%s / template1 / hello.html'%用户名)

用户名可以在视图中进行改变。当然你也可以在那里选择要渲染的模板(1或2)。但基本上你真正想念的是这个自定义路径的自定义Jinja加载器。

希望帮助或给出的想法:

By default flask uses template files stored in "template" directory :

/flaskapp
    /application.py
    /templates
        /hello.html

Is there any way to dynamically choose template directory according to user logged in? This is how I want the directory structure to be :

/flaskapp
    /application.py
    /templates (default template goes here)
        /hello.html
    /userdata
        /user1
            /template1
                 hello.html
            /template2
                 hello.html
        /user2
            /template1
                 hello.html
            /template2
                 hello.html

Now if I have the username of logged in user and the name of template activated by user, is it possible to dynamically select the directory to load template files? For example,

/userdata/<username>/<activated template name>/

instead of fixed

/templates/

What I am trying to achieve is a wordpress like theme system for my web application where users can upload/select themes for his website.

解决方案

There is also the possibility to overwrite Jinja loader and set the paths where Jinja will look for the templates. Like:

my_loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader(['/flaskapp/userdata', 
                                 '/flaskapp/templates']),
    ])
app.jinja_loader = my_loader

Directories are arranged in the order where Jinja needs to first start looking for it. Then from the view you can render user specific template like this:

render_template('%s/template1/hello.html' % username)

where username you can dinamically change in the view. Of course you can also there choose which template (1 or 2) to render. But basically what you really miss is this custom Jinja loader with the custom paths.

Hope that helped or gave the ideas :)

这篇关于如何动态选择要在烧瓶中使用的模板目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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