21.10.2015 Views

1-33

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Symfony2 – Franz Jordán 2011<br />

// src/Acme/ArticleBundle/Controller/ArticleController.php<br />

class ArticleController extends Controller<br />

{<br />

public function recentArticlesAction($max = 3)<br />

{<br />

// make a database call or other logic to get the "$max" most recent articles<br />

$articles = ...;<br />

return $this->render('AcmeArticleBundle:Article:recentList.html.twig', array('articles' =><br />

$articles));<br />

}<br />

}<br />

The recentList template is perfectly straightforward:<br />

{# src/Acme/ArticleBundle/Resources/views/Article/recentList.html.twig #}<br />

{% for article in articles %}<br />

<br />

{{ article.title }}<br />

<br />

{% endfor %}<br />

Notice that we've cheated and hardcoded the article URL in this example<br />

(e.g./article/*slug*). This is a bad practice. In the next section, you'll learn how to do this<br />

correctly.<br />

To include the controller, you'll need to refer to it using the standard string syntax for<br />

controllers (i.e. bundle:controller:action):<br />

{# app/Resources/views/base.html.twig #}<br />

...<br />

<br />

{% render "AcmeArticleBundle:Article:recentArticles" with {'max': 3} %}<br />

<br />

Whenever you find that you need a variable or a piece of information that you don't have access<br />

to in a template, consider rendering a controller. Controllers are fast to execute and promote<br />

good code organization and reuse.<br />

Linking to Pages<br />

Creating links to other pages in your application is one of the most common jobs for a template.<br />

Instead of hardcoding URLs in templates, use the path Twig function (or the router helper in<br />

PHP) to generate URLs based on the routing configuration. Later, if you want to modify the URL<br />

of a particular page, all you'll need to do is change the routing configuration; the templates will<br />

automatically generate the new URL.<br />

First, link to the "_welcome" page, which is accessible via the following routing configuration:<br />

_welcome:<br />

pattern: /<br />

defaults: { _controller: AcmeDemoBundle:Welcome:index }<br />

75

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

Saved successfully!

Ooh no, something went wrong!