A very basic tutorial?

4,549 views
Skip to first unread message

Marc ThinlineData

unread,
Oct 4, 2012, 3:47:32 PM10/4/12
to mako-d...@googlegroups.com
I am just about to dive into Mako, but one thing that is not clearly defined is the entire template model. 

For those of us that dont come from an MVC background it would be sweet to have access to some very basic tutorials in how Python is actually inserted into the html's and how it exactly behaves server side and client side (from a file location point of view). I am still not sure how to utilize Mako, other than that I can embed Python into html like php. But question is now, what do I do? 

Hope someone can help me through this difficult period, heh :)

Michael Bayer

unread,
Oct 6, 2012, 10:37:35 AM10/6/12
to mako-d...@googlegroups.com
Well if you want to understand it from a Python perspective, there's a good path for that which is the .code attribute. I'm always puzzled when other compiled template langs and such don't give you quick access to this, but here's how to see what's going on:

>>> from mako.template import Template
>>> t = Template("hello world")
>>> print t.code

(check out the code for the template)

>>> t = Template("""
... before
... <%
... x = 5
... %>
... after
... """)
>>> print t.code

(check out this one)

>>> print Template("this is a ${variable}").code

(more code !)

basically, make any Template, print out the .code attribute, and that's the Python. Things you should see here are the structure of your template set up as a Python function, the basic "private" names such as __M_locals and __M_writer, comments that allow Mako to cross-reference generated Python lines back to the source template (used in exception reporting). If you play around with <%def>, <%block>, <%inherits> you'll see even more going on and ultimately it starts rendering code that I barely understand several years after writing it :).


Hollister

unread,
Oct 7, 2012, 9:47:43 PM10/7/12
to mako-d...@googlegroups.com
For web applications, I believe most people use Mako as the templating language to a web framework such as Pyramid, Django or Turbogears, rather than just by itself (although you can do that). So, for an MVC app, the framework allows you to build the Model and Controllers, using Mako as the Views. The server files for the framework will be Python, with Mako generating Python code as well (per Mike's answer).

The framework also typically has a webserver (or uses one) that responds to HTTP requests, calling the appropriate Controller (via a route), which renders the View (the Mako-generated Python), which will send back HTML to the client. From a file perspective, everything is on the server. HTML is generated and sent to the client on a per-request basis (not taking into account any caching). Of course static client-side files like Javascript or CSS can also be served, but don't necessarily have to involve the app logic.

This is about as basic as I can get but still include all the pieces. Hope it helps you connect some dots.

ps: for help with the Model part of your app, I can highly recommend SQLAlchemy, which also plugs into your framework.

Marc ThinlineData

unread,
Oct 8, 2012, 9:08:36 AM10/8/12
to mako-d...@googlegroups.com
What really confused me was this: http://warp.byu.edu/mako_apache_wsgi_connector.py

The reason for that was that it put me back to square one in regards to Mako. Is Mako by default able to embed Python into html or is it not? And is the modification that this guy has done nothing but allowing .mako file extensions as .php/.jsp? 

My goal was to basically embed Python into HTML, even though this is not the pure pythonic way and MVC is the "way-to-do-it". But for the sake of it, I wanted to play around with embedded Python. Thats why I ended up with Mako, and thats why I suddenly stopped understanding if Mako allows for embedding or not. 

Hollister

unread,
Oct 8, 2012, 10:30:12 AM10/8/12
to mako-d...@googlegroups.com
Right, that script allows you to render Mako templates in direct response to a webserver request, much in the same way PHP does. While it is possible to bake your Model and Controller right into the Mako template, it's not recommended for anything but trivial apps.

So bottom line, yes, Mako allows for Python statements to embedded among the markup, with defs and imports and everything else. Here's s tiny example:

<%!
    ## python module-level code
    import datetime
%>

<%
    ## python code block
    def getDate():
        return datetime.datetime.now()
%>

<h1>It is now ${getDate()}</h1>

Hollister

unread,
Oct 8, 2012, 1:03:26 PM10/8/12
to mako-d...@googlegroups.com
Just for grins and so you don't have to mess with Apache, here is a complete webserver Python program that will render Mako templates:

from wsgiref.simple_server import make_server
from mako.template import Template

def renderTemplate(file):
    template = Template(filename = file, output_encoding = 'ascii')
    return template.render()

def app(environ, start_response):
    start_response('200 OK', [])
    path = environ['PATH_INFO'][1:]     # strip the leading slash
    return '' if path == 'favicon.ico' else [renderTemplate(path)]  # ignore request for favicon

if __name__ == '__main__':
    server = make_server('127.0.0.1', 8080, app)
    server.serve_forever()

Just save this as server.py run it (python server.py). Assuming you have a Mako template named date.mako in the same directory with this content:

<%!
    ## python module-level code
    import datetime
%>
<%
    ## python code block
    def getDate():
        return datetime.datetime.now()
%>
<html><head></head><body>
<h1>It is now ${getDate()}</h1>
</body></html>

You should see the date when you browse to http://localhost:8080/date.mako

Enjoy.



Marc ThinlineData

unread,
Oct 9, 2012, 8:54:17 AM10/9/12
to mako-d...@googlegroups.com
Could we somehow tweak this so that we could call the extension of the files .psp (yes I know about mod_python). 

But this could easily be a version 2.0 if the mako hack works, yet calling the files .mako seems stupid. I want to call them .psp


Hollister

unread,
Oct 9, 2012, 9:06:08 AM10/9/12
to mako-d...@googlegroups.com
Sure, just name them whatever you want.
Just to be clear, this isn't a hack, rather a way to frob and debug mako as you learn. It's a pain in the ass to restart the server each time you make a change. I also figure you're going to want to return data context, serve static files, etc. This I left as an exercise to the reader.
:)

Marc ThinlineData

unread,
Oct 9, 2012, 9:08:18 AM10/9/12
to mako-d...@googlegroups.com
Huh? httpd is a 1 min procedure to reboot. When you say change, I assume you are thinking changing the mako source code files? Is there no way to do this on demand? 

Aww come on, share the spoils. Embedded Python is cool! We all want that! 

Marc ThinlineData

unread,
Oct 9, 2012, 9:09:11 AM10/9/12
to mako-d...@googlegroups.com
Btw. got an email I can get in touch with you on? 

Hollister

unread,
Oct 9, 2012, 9:24:28 AM10/9/12
to mako-d...@googlegroups.com
Right, it's less than a second to do a ctrl-c, python server.py. That's not the point. Most robust frameworks detect changes and issue a restart for you, so you only have to do an F5 in the browser (and some do that for you as well). Also, .mako or .mak extensions are standard for many reasons, server treatment, editor syntax recognition, etc., not "stupid".

Just post here and I'm happy to help as you go, and others can weigh in (maybe even Mr. Bayer himself). As my ex-wife says, "you ain't no expert in everything".
:)

-aw

Marc ThinlineData

unread,
Oct 9, 2012, 9:32:15 AM10/9/12
to mako-d...@googlegroups.com
Well I guess the last thing I need to figure out then is which method is the easiest and most comfortable to work with. This .mako thing or my sidekick thread here: https://groups.google.com/d/topic/modwsgi/LmxUMwUDVaU/discussion where it spurred another "this is how to embed Python in HTML" solution. 

What do you reckon? 

Hollister

unread,
Oct 9, 2012, 9:44:04 AM10/9/12
to mako-d...@googlegroups.com
Ok, I think all of us on basically on the same page: Python is great, wsgi is great, Mako is great, but you need to have a web framework to do anything significant. I personally like Pyramid, but the learning curve is damn near crippling. You may want to look at Django, which gets you up and running very quickly, and shields you from the plumbing of the app so you can focus on the actual functionality. Really, I think you can get an app running in like 2 mins, then just build your shit.

Hollister

unread,
Oct 9, 2012, 9:49:02 AM10/9/12
to mako-d...@googlegroups.com
Also, (and I don't know what kind of app you're building), but I find that most of my time is spent on client code these days. Not that the backend is not important, but that there are a lot of other things to consider. I now use LESS for css, Handlebars for client-side templating, JQuery of course, etc.

Hollister

unread,
Oct 9, 2012, 10:35:02 AM10/9/12
to mako-d...@googlegroups.com
I agree, your access to the machinery is incredibly useful to non-trivial dev. I've been trying to get this to work within Pyramid, which obviously calls TemplateLookup and Template on my behalf, but I'm missing something. When I access the lookup property within the template code, I don't get the introspection object I think I want. I'd like to be able to log.debug(context.lookup.get_template("this template right now").code) kind of thing. Can you give me a hint how to proceed?

alfonso olavarria

unread,
May 14, 2013, 12:10:06 PM5/14/13
to mako-d...@googlegroups.com
Hello, I want to know if I can help.

in mako do not know how to compare objects that I bring.
instance.

% for order in objects:

with this I shall recorer all fields of objects, but I need to make comparisons or summations of fields.

for example like this is wrong.

% for order in object:
$ {orden.total} = $ {orden.total} + $ {orden.campo}
% endfor
Reply all
Reply to author
Forward
0 new messages