Using javascript in Symfony2/Twig(在 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 文件中作为 bundles 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...
});
}
});
然后我使用资产将这些文件包含在我的基本模板中:
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> 的末尾有一个块用于 $(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Symfony2/Twig 中使用 javascript
基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
