Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Templating
  4. How to Work with Different Output Formats in Templates
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

How to Work with Different Output Formats in Templates

Edit this page

Warning: You are browsing the documentation for Symfony 3.2, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

How to Work with Different Output Formats in Templates

Templates are a generic way to render content in any format. While in most cases you'll use templates to render HTML content, a template can just as easily generate JavaScript, CSS, XML or any other format you can dream of.

For example, the same "resource" is often rendered in several formats. To render an article index page in XML, simply include the format in the template name:

  • XML template name: article/show.xml.twig
  • XML template filename: show.xml.twig

In reality, this is nothing more than a naming convention and the template isn't actually rendered differently based on its format.

In many cases, you may want to allow a single controller to render multiple different formats based on the "request format". For that reason, a common pattern is to do the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// ...
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class ArticleController extends Controller
{
    /**
     * @Route("/{slug}")
     */
    public function showAction(Request $request, $slug)
    {
        // retrieve the article based on $slug
        $article = ...;

        $format = $request->getRequestFormat();

        return $this->render('article/show.'.$format.'.twig', array(
            'article' => $article,
        ));
    }
}

The getRequestFormat() on the Request object defaults to html, but can return any other format based on the format requested by the user. The request format is most often managed by the routing, where a route can be configured so that /about-us sets the request format to html while /about-us.xml sets the format to xml. This can be achieved by using the special _format placeholder in your route definition:

1
2
3
4
5
6
7
/**
 * @Route("/{slug}.{_format}", defaults={"_format": "html"})
 */
public function showAction(Request $request, $slug)
{
    // ...
}

Now, include the _format placeholder when generating a route for another format:

  • Twig
  • PHP
1
2
3
<a href="{{ path('article_show', {'slug': 'about-us', '_format': 'xml'}) }}">
    View as XML
</a>
1
2
3
4
5
6
7
8
<!-- The path() method was introduced in Symfony 2.8. Prior to 2.8, you
     had to use generate(). -->
<a href="<?php echo $view['router']->path('article_show', array(
    'slug' => 'about-us',
    '_format' => 'xml',
)) ?>">
    View as XML
</a>

See also

For more information, see this Advanced Routing Example.

Tip

When building APIs, using file name extensions often isn't the best solution. The FOSRestBundle provides a request listener that uses content negotiation. For more information, check out the bundle's Request Format Listener documentation.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Measure & Improve Symfony Code Performance

    Measure & Improve Symfony Code Performance

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Youpie, a Symfony contributor

    Thanks Youpie for being a Symfony contributor

    1 commit • 3 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia