使用可变路由在Symfony2中提供静态html

时间:2016-11-04 05:25:49

标签: symfony

在Symfony2的routing.yml中,我知道可以路由到静态HTML页面,如下所示:

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

我的问题是,有没有办法在routing.yml使用FrameworkBundle:Template:template进行变量路由?

像这样(不起作用,只是我想做的图像):

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

然后/mycomponents/foobar.html会加载@StubbornShowaBundle/Resources/public/imports/foobar.html

这可能吗? (如果是这样,我该怎么做?)

3 个答案:

答案 0 :(得分:1)

您需要创建自定义控制器:

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));
        }
    }
}

定义路线如:

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

答案 1 :(得分:0)

让模板由控制器决定。您可以将变量file传递给Controller。

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

这样,将呈现从网址收到的动态模板文件名。

希望这有帮助!

答案 2 :(得分:0)

您可以拥有管理所有内容的模板,也可以使用它来委托其他辅助模板。

{% 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 %}