V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
DAOCLOUD
推荐学习书目
Python Cookbook
Using Google App Engine
推荐下载
Latest Google App Engine SDK
其他兼容技术
AppScale
darasion
V2EX  ›  Google App Engine

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

  •  
  •   darasion · 2011-03-10 00:22:15 +08:00 · 5144 次点击
    这是一个创建于 4818 天前的主题,其中的信息可能已经有所发展或是发生改变。
    试着迁移 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


    这个该怎样解决呢?
    2 条回复    1970-01-01 08:00:00 +08:00
    darasion
        1
    darasion  
    OP
       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
        2
    lepture  
       2011-03-10 11:18:03 +08:00
    不能。。

    以上层作为 template dir 。

    render 的时候到下一层咯。 render("xxx/xxx.html")
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2527 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 07:52 · PVG 15:52 · LAX 00:52 · JFK 03:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.