Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to template like ERB in Python? [closed]

Tags:

python

jinja2

ERB, if you're not familiar with it, is the templating language used by Ruby On Rails and many other Ruby projects. In short, it allows you to evaluate raw ruby code inside HTML templates and render the result.

Consider the following:

#hello.erb
<html>
<body>
  <p>Hello, <%= @name %></p>
</body>
<html>

The Ruby instance variable @name would get replaced and rendered out onto the page seen by users.

Now, Python has a common templating language known as Jinja2 which works in almost the same way (mostly using {{ }}s instead of <% %>s), but there's one massive difference between the two:

ERB allows you to use any valid Ruby code, while Jinja2 only has a very limited subset of Python-esque language, but not raw Python.

The question:

How do you template HTML with Python, using the entire language, rather than a limited subset?

like image 233
Mikey T.K. Avatar asked Jan 30 '16 16:01

Mikey T.K.


People also ask

How do you create a template in Python?

The Python string Template is created by passing the template string to its constructor. It supports $-based substitutions. This class has 2 key methods: substitute(mapping, **kwds): This method performs substitutions using a dictionary with a process similar to key-based mapping objects.

What is ERB templating?

An ERB template looks like a plain-text document interspersed with tags containing Ruby code. When evaluated, this tagged code can modify text in the template. Puppet passes data to templates via special objects and variables, which you can use in the tagged Ruby code to control the templates' output.

What is ERB extension?

Script written in ERB, a templating language for Ruby; may include any type of plain text or source code, but also includes Ruby ERB code that generates additional text into the resulting file when run with the ERB template engine. ERB is often used for templating Web files such as . RB, . RHTML, .

What does ERB stand for in File_name ERB?

ERB stands for Embedded Ruby.


1 Answers

Mako allows to write a regular block of Python code, like this

this is a template
<%
    x = db.get_resource('foo')
    y = [z.element for z in x if x.frobnizzle==5]
%>
% for elem in y:
    element: ${elem}
% endfor

http://docs.makotemplates.org/en/latest/syntax.html#python-blocks

like image 178
r-m-n Avatar answered Sep 28 '22 20:09

r-m-n