在Symfony2 / Twig中使用javascript [英] Using javascript in Symfony2/Twig

查看:90
本文介绍了在Symfony2 / Twig中使用javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为contact.html.twig的视图。它有一个包含一些文本字段的表单。我想使用javascript来验证没有字段是空的,以及其他一些规则。但我不知道在哪里放置.js的定义。我不知道如何使用Twig表示法调用.js脚本。

I have a view called contact.html.twig. It has a form with some textfields. I want to use javascript to validate that none of the fields are empty, as well as some other rules. But I do not know where to put the .js with the definitions. I do not know either how to call the .js script using the Twig notation.

推荐答案

这是如何使用的通用答案处理javascript ...不是特别是验证部分。我使用的方法是将单独的功能存储在单独的JS文件中作为插件 Resources / public / js 目录中的插件,如下所示:

This is a generic answer for how to handle javascript... not specifically the validation part. The approach I use is to store individual functionality in separate JS files as plugins in the bundles Resources/public/js directory like so:

(function ($) {

    $.fn.userAdmin = function (options) {
        var $this = $(this);

        $this.on('click', '.delete-item', function (event) {
            event.preventDefault();
            event.stopPropagation();

            // handle deleting an item...
        });
    }
});

然后我使用assetic将这些文件包含在我的基本模板中:

I then include these files in my base template using assetic:

{% javascripts
    '@SOTBCoreBundle/Resources/public/js/user.js'
%}
    <script src="{{ asset_url }}"></script>
{% endjavascripts %}

在我的基本模板中,我在结尾处有一个块< body> for $(document).ready();

In my base template I have a block at the end of <body> for a $(document).ready();

<script>
    $(document).ready(function () {
        {% block documentReady %}{% endblock documentReady %}
    });
</script>
</body>

然后在我的具有用户管理功能的页面中,我可以像这样调用userAdmin函数:

Then in my page that has the "user admin" functionality I can call the userAdmin function like so:

{% block documentReady %}
    {{ parent() }}
    $('#user-form').userAdmin();
{% endblock documentReady %}

这篇关于在Symfony2 / Twig中使用javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆