Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a native templating system for plain text files in Python?

I am looking for either technique or templating system for Python for formatting output to simple text. What I require is that it will be able to iterate through multiple lists or dicts. It would be nice if I would be able to define template into separate file (like output.templ) instead of hardcoding it into source code.

As simple example what I want to achieve, we have variables title, subtitle and list

title = 'foo' subtitle = 'bar' list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] 

And running throught a template, output would look like this:

Foo Bar  Monday Tuesday Wednesday Thursday Friday Saturday Sunday 

How to do this? Thank you.

like image 297
Gargauth Avatar asked Jun 17 '11 12:06

Gargauth


People also ask

Is there Templates in Python?

In python, template is a class of String module. It allows for data to change without having to edit the application. It can be modified with subclasses. Templates provide simpler string substitutions as described in PEP 292.

What is Python templating?

Templating, and in particular web templating is a way to represent data in different forms. These forms often (but not always) intended to be readable, even attractive, to a human audience. Frequently, templating solutions involve a document (the template) and data.


1 Answers

You can use the standard library string an its Template class.

Having a file foo.txt:

$title $subtitle $list 

And the processing of the file (example.py):

from string import Template  d = {     'title': 'This is the title',     'subtitle': 'And this is the subtitle',     'list': '\n'.join(['first', 'second', 'third']) }  with open('foo.txt', 'r') as f:     src = Template(f.read())     result = src.substitute(d)     print(result) 

Then run it:

$ python example.py This is the title And this is the subtitle first second third 
like image 70
ThibThib Avatar answered Sep 30 '22 06:09

ThibThib