21.10.2015 Views

1-33

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Symfony2 – Franz Jordán 2011<br />

{# src/Acme/BlogBundle/Resources/views/Blog/index.html.twig #}<br />

{% extends 'AcmeBlogBundle::layout.html.twig' %}<br />

{% block content %}<br />

{% for entry in blog_entries %}<br />

{{ entry.title }}<br />

{{ entry.body }}<br />

{% endfor %}<br />

{% endblock %}<br />

Notice that this template extends the section template -<br />

(AcmeBlogBundle::layout.html.twig) which in-turn extends the base application layout<br />

(::base.html.twig). This is the common three-level inheritance model.<br />

When building your application, you may choose to follow this method or simply make each<br />

page template extend the base application template directly<br />

(e.g. {% extends '::base.html.twig' %}). The three-template model is a best-practice<br />

method used by vendor bundles so that the base template for a bundle can be easily overridden<br />

to properly extend your application's base layout.<br />

Output Escaping<br />

When generating HTML from a template, there is always a risk that a template variable may<br />

output unintended HTML or dangerous client-side code. The result is that dynamic content<br />

could break the HTML of the resulting page or allow a malicious user to perform a Cross Site<br />

Scripting (XSS) attack. Consider this classic example:<br />

Hello {{ name }}<br />

Imagine that the user enters the following code as his/her name:<br />

alert('hello!')<br />

Without any output escaping, the resulting template will cause a JavaScript alert box to pop up:<br />

Hello alert('hello!')<br />

And while this seems harmless, if a user can get this far, that same user should also be able to<br />

write JavaScript that performs malicious actions inside the secure area of an unknowing,<br />

legitimate user.<br />

The answer to the problem is output escaping. With output escaping on, the same template will<br />

render harmlessly, and literally print the script tag to the screen:<br />

Hello &lt;script&gt;alert(&#39;helloe&#39;)&lt;/script&gt;<br />

The Twig and PHP templating systems approach the problem in different ways. If you're using<br />

Twig, output escaping is on by default and you're protected. In PHP, output escaping is not<br />

automatic, meaning you'll need to manually escape where necessary.<br />

Output Escaping in Twig<br />

If you're using Twig templates, then output escaping is on by default. This means that you're<br />

protected out-of-the-box from the unintentional consequences of user-submitted code. By<br />

default, the output escaping assumes that content is being escaped for HTML output.<br />

80

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!