1
votes

In Symfony2's routing.yml, I understand it's possible to route to a static HTML page, like this:

my_static_route:
    path:     /mycomponent
    defaults:
        _controller: FrameworkBundle:Template:template
        template:    @StubbornShowaBundle/Resources/public/imports/component.html

My question is, is there any way to do variable routing in routing.yml using FrameworkBundle:Template:template?

Like this(doesn't work, just an image of what I want to do):

my_static_route:
    path:     /mycomponents/{file}
    defaults:
        _controller: FrameworkBundle:Template:template
        template:    @StubbornShowaBundle/Resources/public/imports/{file}

And then /mycomponents/foobar.html would load @StubbornShowaBundle/Resources/public/imports/foobar.html

Is that possible? (And if so, how do I do that?)

3

3 Answers

1
votes

You need to create custom controller:

namespace Stubborn\ShowaBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class StaticController extends Controller
{
    public function streamAction($filename)
    {
        try {
            $path = $this->container->get('kernel')->locateResource('@StubbornShowaBundle/Resources/public/imports/' . $filename);
            $response = new BinaryFileResponse($path);

            return $response;
        } catch (\InvalidArgumentException $e) {
            throw $this->createNotFoundException(sprintf("File '%s' not exists!", $filename));
        }
    }
}

And define route like:

my_static_route:
    path:     /mycomponents/{filename}
    defaults:
        _controller: StubbornShowaBundle:Static:stream
0
votes

Let the template decided by controller. You can pass variable file to Controller.

// In your TemplateController.
public function templateAction($file)
{
    return $this->render('@StubbornShowaBundle/Resources/public/imports/' . $file);
}

This way, the dynamic template file name received from the url will be rendered.

Hope this helps!

0
votes

You could either have a template that managed everything or use it to delegate to other secondary templates.

{% extends 'WhatEver.html.twig' %}

{% block something %}
    {# handle in template #}
    {% if 'value' == file %}
        <ul>
            <li>{{file}}</li>
            <li>Whatever</li>
            <li>You</li>
            <li>Would</li>
            <li>Have</li>
            <li>In</li>
            <li>The</li>
            <li>Template</li>
        </ul>
    {% else %}
        <div class="alert">
            File "{{file}}" not recognised!
        </div>
    {% endif %}

    {# delegate to separate template #}
    {{ include('@StubbornShowaBundle/Resources/public/imports/' ~ file, ignore_missing = true) }}
    {# or maybe (to add the extension) #}
    {{ include('@StubbornShowaBundle/Resources/public/imports/' ~ file ~ '.html.twig', ignore_missing = true) }}
{% endblock %}