如何在Symfony2路由中定义默认日期值? [英] How to define default date values in Symfony2 routes?

查看:72
本文介绍了如何在Symfony2路由中定义默认日期值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要创建以年,月和日为变量的路线,如何定义这些变量为空,应采用当前日期?

If I want to create a route, where the year, month and date are variables, how can I define that if these variables are empty, the current date shall be taken?

例如像这样(肯定不能正常工作...)

E.g. like this (doesn't work for sure...)

blog:
    path:      /blog/{year}/{month}/{day}
    defaults:  { _controller: AcmeBlogBundle:Blog:index,
                    year:  current_year,
                    month: current_month
                    day:   current_day
               }

我考虑过定义两条不同的路线,例如

I thought about defining two different routes, like this

blog_current_day:
    path:      /blog
    defaults:  { _controller: AcmeBlogBundle:Blog:index }

blog:
    path:      /blog/{year}/{month}/{day}
    defaults:  { _controller: AcmeBlogBundle:Blog:index }

但是如果我随后致电 blog_current_day 我的控制器

But if I then call blog_current_day my controller

public function indexAction(Request $request, $year, $month, $day) {
    // ...
}

将抛出异常,因为年,月和日是密西ng。

will throw an exception because year, month and day are missing.

有什么建议吗?

推荐答案

动态容器参数

您可以设置容器参数在位于 Acme\BlogBu​​ndle\DependencyInjection\AcmeBlogExtension 的捆绑包扩展名中动态地进行设置,之后,您可以在路由中使用这些参数,例如%parameter %

Dynamic Container Parameters

You can set container parameters dynamically in your bundle's extension located Acme\BlogBundle\DependencyInjection\AcmeBlogExtension afterwards you can use those parameters in your routes like %parameter%.

namespace Acme\BlogBundle\DependencyInjection;

use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class AcmeBlogExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $container->setParameter(
            'current_year',
            date("Y")
        );

        $container->setParameter(
            'current_month',
            date("m")
        );

        $container->setParameter(
            'current_day',
            date("d")
        );
    }
}



路由配置



Routing Configuration

blog:
    path:      /blog/{year}/{month}/{day}
    defaults:  { _controller: AcmeBlogBundle:Blog:index, year: %current_year%, month: %current_month%, day: %current_day% }



静态参数



如果只需要可配置的静态参数,则可以将其添加到 config.yml 中。

parameters:
    static_parameter: "whatever"

...然后在您的路由中再次访问它们,例如%static_parameter%

... then again access them in your routing like %static_parameter%.

这篇关于如何在Symfony2路由中定义默认日期值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆