简体   繁体   中英

How to use inheritance with mako using non-file based templates?

Most of the examples and tutorials for mako suggest you use files for templates.

How can I use inheritance, if the templates are stored in strings or in a database?

As a starting point I am trying to create a variable based inheritance example based on the file-based inheritance example from the mako website (which could be easily converted to a database-based example afterwards):

from mako.template import Template

base = """
  <html>
    <body>

      <div class="header">
        <%block name="header"/>
      </div>

      Some body content ...

    </body>
  </html>
"""

index = """
  <%inherit file="base.html"/>

  <%block name="header">
    this is some header content
  </%block>

  this is the body content.
"""

base_template = Template(base)
index_template = Template(index)

print index_template.render()

Obviously this does not work.

The second template needs some way to know that base.html should be base_template.

This question has also been asked on the mako-discuss group in 2009:

https://groups.google.com/d/topic/mako-discuss/QiwkRu7rTFQ/discussion

This is what Michael Bayer wrote as an answer:

A TemplateLookup collection needs to be involved for templates to
access each other.

Any template can be associated with a lookup using either the "lookup=some_lookup" keyword argument sent to Template, or by creating the Template strings directly with the lookup using lookup.put("some template name", "your template").

I could not yet figure out how to apply this and convert it to actual python code.

First of all you need to add ${self.body()} to your base template, this will mark the place there the inheritor's data will go. And then you can use TemplateLookup like so:

from mako.template import Template
from mako.lookup import TemplateLookup

base = """
  <html>
    <body>

      <div class="header">
        <%block name="header"/>
      </div>

      ${self.body()}

    </body>
  </html>
"""

index = """
  <%inherit file="base.html"/>

  <%block name="header">
    this is some header content
  </%block>

  this is the body content.
"""

lookup = TemplateLookup()
lookup.put_string("base.html", base)
lookup.put_string("index.html", index)

index_template = lookup.get_template("index.html")

print index_template.render()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM