2

I have a big html file named exercise.html, I need generate to one som stuff by Python CGI. I want to ask you what is the best way to print this HTML.

I know that it is possible by print method with using format methods %s, %i etc.:

print '''<html>
<head><title>My first Python CGI app</title></head>
<body> 
<p>Hello, 'world'!</p>
.
.
<div>%s</div>
.
.
</body>
</html>''' % generated_text

But this HTML is really big,so is this only one solution?

2 Answers 2

2

You should consider using a templating language like Jinja2.

Here is a simple example straight from the link above:

>>> from jinja2 import Template
>>> template = Template('Hello {{ name }}!')
>>> template.render(name='John Doe')

Generally, though you save templates in a file, and then load / process them:

from jinja2 import Environment, PackageLoader
# The env object below finds templates that are lcated in the `templates`
# directory of your `yourapplication` package.
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
template = env.get_template('mytemplate.html')
print template.render(the='variables', go='here')

As demonstrated above, templates let you put variables into the template. Placing text inside {{ }} makes it a template variable. When you render the template, pass in the variable value with a keyword argument. For instance, the template below has a name variable that we pass via template.render

This is my {{name}}.

template.render(name='Jaime')
Sign up to request clarification or add additional context in comments.

Comments

1

Also consider Python Bottle (SimpleTemplate Engine). It is worth noting that bottle.py supports mako, jinja2 and cheetah templates.

The % indicates python code and the {{var}} are the substitution variables

HTML:

<ul>
  % for item in basket:
  <li>{{item}}</li>
  % end
</ul>

Python:

with open('index.html', 'r') as htmlFile:
    return bottle.template(htmlFile.read(), basket=['item1', 'item2'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.