Yii2: Yii2 js router?

Created on 10 Mar 2015  路  11Comments  路  Source: yiisoft/yii2

Are there any plans or is there already something like JS router in Yii2 (meaning generating url routes with javascript)?

Most helpful comment

For instance if I have to generate url in js script what is the best way to do it without knowing if pretty urls are on or not?

All 11 comments

No, there's nothing like that currently.

What's use case for it?

You can generate the url in php, and get it in javascript.

For instance if I have to generate url in js script what is the best way to do it without knowing if pretty urls are on or not?

Current options:

  • If you are generating the JS via PHP then you can use yii's PHP methods (e.g. Url helper) to generate the Url and use it in your client script. e.g.
$view->registerJs('$("#input-id").plugin({url:"' . Url::to(['/site/test']) . '"});');
  • If you want to use URL at runtime in javascript... one way is to store the URL in HTML5 data attributes via PHP again:
<input id="input-id" data-url='<?= Url::to(['/site/test']) ?>'>

then in your javascript

function doSomething() {
    var vUrl = $("#input-id").data('url'), vData;
    $.ajax({
        url: vUrl,
        type: 'post',
        data: vData
    });
}

Well, thoretically Rules could be converted to JS but I'm not sure how to deal with custom ones, rest ones etc.

Initially, I went with @kartik-v first option but was wondering if there is a slimmer solution. It is much nicer when you have a single Asset class for your client script. In either the first or the second options I have to register js separately from the Asset file and it is not that nice. Anyway thanks @kartik-v @samdark

+1

I'd love to see something like Rails js-routes: https://github.com/railsware/js-routes

Trying to pass all sorts of urls and routes to javascript doesn't work well with an angular single page application.

+1
Like this
Yii.app.createUrl('admin/device/deleteDeviceCategory')
Yii.app.createUrl({path: 'admin/device/deleteDeviceCategory', id: 100})

+1

In case you want to navigate based on a select value, you need to generate de Url in JavaScript.

I have this approach in JS:

Url is generated on server, and values on client javascript.

Was this page helpful?
0 / 5 - 0 ratings