Enhance the Django template with Mako, using a JSP like

Source: Internet
Author: User
Tags python string format

Enhanced Django templates with Mako

Django Default template functionality is also possible, but not directly with the Python syntax, mako solve the pain point,
Makes Django templates look like JSPs and can do things directly using Python's syntax.

Mako
Django-mako
Demo

Mako Basic usageMako's template needs to be done this way.
    1. A direct look like the Python string format

      From mako.template Import Template
      MyTemplate = Template ("Hello, ${name}!")
      Print Mytemplate.render (name= "Jack")

    2. With file

      From mako.template Import Template

      MyTemplate = Template (filename= '/docs/mytmpl.txt ', module_directory= '/tmp/mako_modules ')
      Print Mytemplate.render ()

    3. When you need to inherit or search for other template files, you need to templatelookup

      From mako.template Import Template
      From Mako.lookup import Templatelookup

      Mylookup = Templatelookup (directories=['/docs ')
      MyTemplate = Template ("" "<%include file=" header.txt "/> Hello world!" "",
      Lookup=mylookup)

Feeling very complicated, the advent of Django-mako reduced these tedious things to 0, allowing Django to still use Render_to_response

After using Django-mako

A simple view

From djangomako.shortcuts Import render_to_responsedef Index (Request):    return Render_to_response (' index.html ', { })

Index.html

<%! Import OS%><%    rows = [[V for V in Range (0,10)] for row in range (0,10)]%><%def name= "Makerow (Row)" >
   
    <tr>    % for name in row:        <td>${name}</td>    % endfor    </tr></%def>< html>  <body>    ${os.path.sep}    <table>        % for row in rows:            ${makerow (Row)}        % ENDfor    </table>  </body>

This can be called because Django-mako has such a middleware, in the settings.py to join the middleware can easily use the MAKO syntax

From mako.lookup import Templatelookupimport tempfileclass Makomiddleware (object): Def __init__ (self): "" "Setup Mako variables and Lookup object "" "from django.conf Import settings # Set All Mako variables based on Djang o Settings Global template_dirs, output_encoding, module_directory, encoding_errors directories = GetAt TR (settings, ' Mako_template_dirs ', settings.  Template_dirs) Module_directory = getattr (settings, ' Mako_module_dir ', Tempfile.mkdtemp ()) output_encoding = GetAttr (settings, ' mako_output_encoding ', ' utf-8 ') encoding_errors = getattr (settings, ' mako_encoding_errors ', '                                Replace ') Global lookup lookup = Templatelookup (directories=directories,.                                Module_directory=module_directory, Output_encoding=output_encoding,.      Encoding_errors=encoding_errors,) Import Djangomako  Djangomako.lookup = Lookup 
The syntax of Mako

Document

    • Comments

      <%doc>

      These is Commentsmore comments

    • An expression

      ${expression}: ${2*3}–> 6
      ${pow (x,2) + POW (y,2)}

    • Control

      % for a in [' One ', ' one ', ' three ', ' four ', ' five ']:

      % if a[0] = = ' t ': its-or three% elif a[0] = = ' F ': four/five% else:one% endif

      % ENDfor

    • code block

      <%! %> and <%%> are not the same, <%! %> is only loaded once, so it's like defining a method, import something, and write it in here.
      <%!

      Import Mylibimport redef Filter (text):    return re.sub (R ' ^@ ', ', text)

      %>
      <%

      x = Db.get_resource (' foo ') y = [z.element for z in x if x.frobnizzle==5]

      %>

Enhance the Django template with Mako, using a JSP like

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.