Question

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.

Was it helpful?

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)
]

OTHER TIPS

<%
    context.write("Hai")
%>

You can print to the context object:

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

It looks like you just enter the text you want without the print command...

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

http://docs.makotemplates.org/en/latest/defs.html#using-defs

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top