简体   繁体   中英

how to use symfony controller variables in frontend js?

Say I have a controller like this:

public function showAction(Request $request, $id, $context = array())
{
    $url = $this->getPlayUrl($id, $context);

    //some code here}

I want to use the variable $url in a frontend js file like this :

var html = '<iframe src=\''+ url +'\' name=\'viewerIframe\' id=\'viewerIframe\' width=\'100%\'allowfullscreen webkitallowfullscreen height=\'100%\' style=\'border:0px\'></iframe>';

How am I supposed to make this happen? For the code above ,it gave me 'undefined url' error.

Thank you.

In you view add some script tags and assign a javascript vraible to the twig variable. Don't forget to quote the twig (if required).

Firstly, I would ensure that the $url always had a value;

return $this->render('MyWebBundle:Player:show.html.twig', array(
        'file'             => $file,
        'url'              => (empty($url)) ? '' : $url,
        'context'          => $context,
        'player'           => $player,
        'agentInWhiteList' => $agentInWhiteList
    ));

Something like;

<script>
var jsVar = '{{ url }}';
var html = false;

if (jsVar.length > 0) {
    html = '<iframe src=\''+ jsVar +'\' name=\'viewerIframe\' id=\'viewerIframe\' width=\'100%\'allowfullscreen webkitallowfullscreen height=\'100%\' style=\'border:0px\'></iframe>';
}

// test html !== false before using it
</script>

如果您使用HTML5数据属性,则可能会更好: https//developer.mozilla.org/zh-CN/docs/Web/Guide/HTML/Using_data_attributes

Another option would be to have your template call a controller action (so you can pass parameters as required), for example, like this example for using highchart.js:

{% block javascripts %}
    {{ parent() }}
    <script src="/js/highcharts.js"></script>
    <script src="/js/exporting.js"></script>
    <script type="text/javascript">
        {{ render(controller('AppBundle:Default:script')) }}
    </script>
{% endblock %}

In the controller it looks like this:

public function scriptAction() {
    $reports = $this->get('app.reports');
    $chart = $reports->getDistsFYToDate();

    return $this->render('Default/script.js.twig', array(
                'chart' => $chart,
    ));
}

and script.js.twig looks like this:

$(document).ready(function () {
    var options = {
        chart: {
            type: 'line'
        },
        title: {
            text: 'Distributions, FY{{ chart.fy }} to date'
        },
        xAxis: {
            categories: [{% for category in chart.categories %}{{category|raw}}{%endfor%}]
        },
        yAxis: {
            title: {
                text: 'Distributions'
            }
        },
        series: {{ chart.series|raw }}
    };

    $('#linechart').highcharts(options);
})

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