Search code examples
pythonbottle

Use Embedded python with SimpleTemplate Engine passed as string to template()


I am debugging an application and would like to use the bottle SimpleTemplate to render both HTML and Python. If I use a template as a separate file (views/simple.tpl), then Python is rendered correctly.

If I try passing in Python as a string, I get NameError("name 'demo' is not defined",)

from bottle import template

text = "debugging"
return template(
    "<p>{{text}}</p>" + 
    "% demo = 'hello world'" + 
    "<p>{{demo}}</p>",
    text=text
)

Is this possible?


Solution

  • Lines with embedded Python code must start with %. The problem is that you're using string concatenation, which doesn't preserve newlines. Simply put, that string is equivalent to the following line:

    <p>{{text}}</p>% demo = 'hello world'<p>{{demo}}</p>
    

    Since % isn't the first character, it doesn't mean anything to Bottle.

    Add newlines manually:

    return template(
        "<p>{{text}}</p>\n"
        "% demo = 'hello world'\n" 
        "<p>{{demo}}</p>",
        text=text
    )
    

    As a side note, you can use implicit string literal concatenation (as shown in the code above).