迁移 django 0.96 到 1.2 时,遇到 {% include %} 和 {% extends %} 无法找到模板文件的问题。

2011-03-10 00:22:15 +08:00
 darasion
试着迁移 0.96 到 1.2 ,发现一个问题,Google搜索无果。

假设有这样的目录结构:
project
|--templates
| |--ooxx
| | |--aaa.html
| |--bbb.html

若 abc.html:
{% include "../bbb.html" %}

{% extends "../bbb.html" %}

无效。

这里有个解决办法,但是试过似乎仍然无效:
https://groups.google.com/forum/#!msg/google-appengine-python/YaqfeygoiaI/RtDh9pL6XJQJ


这个该怎样解决呢?
5155 次点击
所在节点    Google App Engine
2 条回复
darasion
2011-03-10 10:18:15 +08:00
自问自答:

读了下django 0.96 和 1.2 的源码,对比了一下 django.template.loaders.file_system 这个模块。
发现 Loader 类的 get_template_sources 方法中,文件路径的结合方式不同。

0.96 使用的是普通的 os.path.join 方法,1.2 使用的是 django.utils._os.safe_join 方法,后者限制不允许使用 base path 外的路径。而 include 和 extends 标签会先从base path开始寻找模板(这也许是bug?),如果路径里边有 “../” 可能会直接跳出这个 base path ,于是就会触发找不到模板的异常:

引用(django.utils._os.safe_join):
def safe_join(base, *paths):
"""
Joins one or more path components to the base path component intelligently.
Returns a normalized, absolute version of the final path.

The final path must be located inside of the base path component (otherwise
a ValueError is raised).
"""
#...

举例:
>>> from django.utils._os import safe_join
>>> safe_join('templates','../bbb.html')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\site-packages\django\utils\_os.py", line 44, in safe_joi
n
raise ValueError('the joined path is located outside of the base path'
ValueError: the joined path is located outside of the base path component
>>>


看来,在 django 1.2 模板中,不能 include 或 extends 上层目录的模板。
lepture
2011-03-10 11:18:03 +08:00
不能。。

以上层作为 template dir 。

render 的时候到下一层咯。 render("xxx/xxx.html")

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/9529

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX