1

I have a really noob question here , in php if u wanted to print something inside html you did something like this

<body>
<div>
<?
echo 'Hi i am inside of a div';
?>
</div>
</body>

How do i do that in python?

1
  • you can also pass a dict using html.format(**d) for multiple placeholders. Commented Jul 29, 2014 at 2:25

1 Answer 1

3

In a simple case you can use string formatting. Put a placeholder into the string and use format() to substitute the placeholder with the actual text:

html = """
<body>
<div>
{text}
</div>
</body>
"""

print html.format(text='Hi i am inside of a div')

In case of complex HTML structures, you can make use of template languages, like jinja2. You would basically have an html template which you would render with the context provided:

import jinja2

env = jinja2.Environment(loader=jinja2.FileSystemLoader('.'))
template = env.get_template('index.html')
print template.render(text='Hi i am inside of a div')

where index.html contains:

<body>
    <div>
    {{ text }}
    </div>
</body>
Sign up to request clarification or add additional context in comments.

3 Comments

what if i have complex templates ?
@Maks if you have complex templates you should look in to using a Web framework like flask, Django or pyramid.
I've been searching and it seems u can use <% ** PYTHON CODE HERE ** %> , but it doesnt seem the work with me

Your Answer

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