Search code examples
pythontemplatescherrypymako

How to use print function with Mako templates


heres my problem:

i define a function named "lorem" that should print out some text:

    <div id="mainpage">
        <%
        def lorem():
            for i in range(0,50):
                print("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam")
        %>
        ${lorem()}
    </div>

But all it does is printing this text on my console, but i want this printed on my site. I´m using cherrypy and Mako with python 3.3.


Solution

  • You should be using the def mako tag it makes life easier.

    <%def name="lorem()">
    % for i in range(0,50):
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam
    % endfor
    </%def>
    <div id="mainpage">
        ${lorem()}
    </div>
    

    Edit: if you want to use a standard python function like you have, you just have to make sure it returns something (print sends output to stdout, not to your mako template).

    <div id="mainpage">
        <%
        def lorem():
            res = []
            for i in range(0,50):
                res.append("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam")
            return ' '.join(res)
        %>
        ${lorem()}
    </div>
    

    or use list comprehension

    return ' '.join([
        "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam"
        for i in range(0,50)
    ]