简体   繁体   English

如何在Symfony2中获取控制器动作的路径?

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

I was practicing symfony2. 我正在练习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. 我想将url: "{{ path('my_test_account_register') }}"替换为url: "{{ path('MyTestBudnle:Account:register') }}" ,但是我失败了。

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. 也许这是一个愚蠢的问题,这是我第一次进入stackoverflow。 So, nice to meet you guys! 所以,很高兴认识你们!

I advice you to use 我建议你使用

url: Routing.generate('state_list'),

Have a look on FOSJsRoutingBundle . 看看FOSJsRoutingBundle

The twig function path() you are (correctly) using, creates the url for a given route name and some optional parameters. 您(正确)使用的树枝函数path()为给定的路由名称和一些可选参数创建url。

A controller can have different routes (and thereby different urls) for the same action. 对于同一操作,控制器可以具有不同的路由(从而有不同的URL)。 Because of this, you cannot use the Bundle:Controller:Action notation, if you want to find out the url for a specific action. 因此,如果要查找特定操作的URL,则不能使用Bundle:Controller: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. path()render()之间的区别在于, render()包括子请求对模板中特定动作的响应。 Because this all happens internally, there is no need to generate an url for this. 由于这都是内部发生的,因此无需为此生成URL。 You can even use render() with actions, that have no route at all. 您甚至可以render()与完全没有路由的动作一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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