猎豹#include不起作用

时间:2012-11-29 08:42:22

标签: python flask cheetah

#include似乎无法正常工作,我收到“500内部服务器错误”。我尝试了没有include的相同代码,将所有代码放在一个文件中,并且它可以工作。我正在使用网络框架Flask

header.tmpl

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>$title</title>

        #for $css in $css_sheets
        <link rel="stylesheet" href="../$css">
        #end for
        #for $js in $js_scripts
        <script src="../$js"></script>
        #end for
    </head>
    <body> 

home.tmpl

#include "header.tmpl"
<p id="x">HELLO</p> 
#include "footer.tmpl"

footer.tmpl

    </body>
</html> 

engine.py

from flask import Flask, redirect, request
from Cheetah.Template import Template

app = Flask(__name__)

css_list = ['css/main.css']
js_list = ['js/main.js']
default_title = 'Default Title'

namespace={
    'css_sheets' : css_list,
    'js_scripts' : js_list,
    'title' : default_title
}

@app.route('/')
def main_route():
    return redirect('/index')

@app.route('/index')
def index():
    namespace['title']= 'THIS IS THE INDEX'
    return render("cheetah/home.tmpl", namespace)

def render(template, context):
    """Helper function to make template rendering less painful."""
    return str(Template(file=template, namespaces=[context]))

if __name__ == "__main__":
    app.run()

我的第二个问题是关于header.tmpl中的$ css和$ js变量:

将$ css设置为'css / main.css'的

<link rel="stylesheet" href="../$css">正常工作

将$ css设置为'../css/main.css'的

<link rel="stylesheet" href="$css">失败,它将其作为纯文本'$ css'读取,而不是获取变量的值。

为什么会这样?

1 个答案:

答案 0 :(得分:0)

问题是#include中使用的路径与调用它的模板(home.tmpl)无关,我认为是这种情况,而是python文件(engine.py)在这种情况下不在同一个位置,所以程序没有找到我试图包含的文件。

../web/engine.py
../web/templates/home.tmpl
../web/templates/header.tmpl
../web/templates/footer.tmpl
../web/css/main.css
../web/js/main.js