Search code examples
pythonflaskcheetah

Cheetah #include not working


#include doesn't seem to be working, I get a "500 Internal Server Error". I tried the same code without the include, putting all the code in one file, and it works. i'm using the web framwork 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()

A secondary question that i have is about the $css and $js variables in header.tmpl:

<link rel="stylesheet" href="../$css"> with $css being set to 'css/main.css' works

<link rel="stylesheet" href="$css"> with $css being set to '../css/main.css' fails, it reads it as plain text '$css' instead of getting the value of the variable.

why is that?


Solution

  • The problem was that the path used in the #include is not relative to the template that calls it (home.tmpl), which i thought was the case, but rather the python file (engine.py) which in this case are not in the same location, so the program was not finding the files i was trying to include.

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