简体   繁体   中英

How to get the path of an action of a controller in Symfony2?

I was practicing symfony2. And i got a problem:

I just made a simple twig page which posts data to an action of the controller, and there is a function(it works):

$.ajax({
    type: 'POST',
    url: "{{ path('my_test_account_register') }}",
    data: account,
    success: function(msg){
        alert("Succeed!");
    },
    error: function(XmlHttpRequest,textStatus, errorThrown){
        alert ("Failed! ");
    }
}

I don't want to add a annotation to every action of mine, howver. I wanted to replace url: "{{ path('my_test_account_register') }}" into url: "{{ path('MyTestBudnle:Account:register') }}" , but i failed.

My question is: how to specify the url of an action inside a controller? Maybe this is a silly question, and this is my first time to stackoverflow. So, nice to meet you guys!

I advice you to use

url: Routing.generate('state_list'),

Have a look on FOSJsRoutingBundle .

The twig function path() you are (correctly) using, creates the url for a given route name and some optional parameters.

A controller can have different routes (and thereby different urls) for the same action. Because of this, you cannot use the Bundle:Controller:Action notation, if you want to find out the url for a specific action. Instead, you have to use the route name.

The difference between path() and render() is, that render() includes the response of a subrequest to a specific action into the template. Because this all happens internally, there is no need to generate an url for this. You can even use render() with actions, that have no route at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM