How to define default date values in Symfony2 routes?

半腔热情 提交于 2019-12-01 04:37:05

问题


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 }

But if I then call blog_current_day my controller

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

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

Any suggestions?


回答1:


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%.

Extension

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

Static Parameters

If you only need configurable static parameters you can just add them to your config.yml.

parameters:
    static_parameter: "whatever"

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




回答2:


You can set $year = null, $month = null, $day = null in controller.

or maybe in route:

year:  null,
month: null,
day:   null,

Then in controller you should get last posts if variables = null, or posts by date.



来源:https://stackoverflow.com/questions/18781708/how-to-define-default-date-values-in-symfony2-routes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!