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="e3sgYXNzZXRfdXJsIH19"></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


- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Flexslider 箭头未正确显示 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01