【问题标题】:How to use JQuery in TWIG (symfony2)如何在 TWIG (symfony2) 中使用 JQuery
【发布时间】:2013-07-16 01:43:13
【问题描述】:

我目前正在尝试在 TWIG 中使用 JQuery。我的网站是使用 Symfony2 创建的。我目前在 TWIG 中有一个表(它可以工作 - 见下文),我想使用 JQuery 来使我的表列可排序。

<table><tr><th>cat</th> <th>dog</th> <th>fish</th> </tr> {% for result in results %}<tr><td>{{result.cat_name}}</td><td>{% for dog in result.dogs %} {{dog.dog_name}}{% endfor %} </td> <td>{% if result.fishs is defined %} {% for fish in result.fishs %}
{{fish.fish_uri}}
  {% endfor %} {% endif %} </td></tr>{% endfor %}

我想利用 DataTables(请参阅 here)从我的表中获取我想要的功能。有一个包(参见here)是为了允许在 TWIG 中使用 DataTables 而创建的。捆绑包已成功安装 (web/bundles/uamdatatables/)。

导致我不确定的原因(因为捆绑包没有使用说明)是我试图使捆绑包工作(使我的表具有 DataTables 提供的功能),但我的表保持不变(也没有错误消息)。

想知道是否有人可以告诉我我做错了什么?我以前从未使用过 JQuery,并且是 Symfony 的新手。我是否需要某种“包含”语句(以获取 js 文件)?

//view.html.twig

<table><table id="table_id" class="display"><thead> {% block stylesheets %}
<link href="{{ asset('/bundles/uamdatatables/css/jquery.dataTables.css') }}" rel="stylesheet" />
<script type="text/javascript" charset="utf-8" src="/bundles/uamdatatables/css/jquery.dataTables.css"></script>
    {% endblock %}<tr><th>cat</th> <th>dog</th> <th>fishs</th> </tr></thead> <tbody><?php $(document).ready( function () {
$('#table_id').dataTable();} );?>{% block javascripts %}
        <script src="{{ asset('/bundles/uamdatatables/js/jquery.dataTables.js') }}"></script>
    {% endblock %}{% for result in results %}<tr><td>{{ result.cat_name}}</td><td>{% for dog in result.dogs %}{{dog.dog_name}}{% endfor %}</td><td>{% if result.fishs is defined %} {% for fish in result.fishs %}{{fish.fish_uri}}{% endfor %}{% endif %}</td></tr>{% endfor %}</tbody> </table>

谢谢! 谭雅

【问题讨论】:

标签: jquery symfony datatables twig


【解决方案1】:

是的,在您的 javascript 块中,您必须包含 jQuery 文件。一个例子:

{% block javascripts %}
    <script type="text/javascript" src="{{ asset('bundles/uamdatatables/js/jquery.min.js') }}"></script>
{% endblock %}

注意不要覆盖继承的javascripts,也许你必须将{{ parent() }}添加到{% block javascripts %}

编辑:

如果您还没有 jQuery 文件,可以从官网下载:http://jquery.com/

【讨论】:

  • 我已将脚本更改为包含 jquery,{% block javascripts %} {% endblock %}。这并没有改变我的页面。然后我继续使用 {{ parent() }} 并得到一个错误; “禁止在不扩展或“使用”另一个模板的模板上调用“父级””。
  • 忘记{{ parent() }}。重点其实就是两点:1-必须在{% block javascripts %}中包含&lt;script type="text/javascript" src="{{ asset('bundles/uamdatatables/js/jquery.min.js') }}"&gt;&lt;/script&gt;不要替换,加那行就行. 2- 你在那个资产位置真的有jquery.min.js 文件吗?如果没有,您可以下载并放在那里,或者,如果您在其他位置有 jQuery 文件,您可以移动它或重命名 asset path
  • 也许下面的代码(下面)不起作用(因此没有使用 JQuery);
  • 我保留了 JQuery 的 2 行,并且 JQuery.min.js 文件确实存在于资产位置.. 该表的加载速度似乎比我页面的其余部分慢 - 有些东西是正在发生。
  • 那个错误是说“我无法识别那个 jQuery 函数”,所以请确保你正确添加了 jQuery 库:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
  • 1970-01-01
相关资源
最近更新 更多