简体   繁体   English

如何在具有 twig 元素的外部文件中使用 javascript 代码?

[英]How can I use javascript code in an external file with twig elements?

I have a lot of javascript code one my twig template home.html.twig , for example:我有很多 javascript 代码一个我的 twig 模板home.html.twig示例

$(document).ready(function () {

  var table = $('.datatable').DataTable({
        "responsive": true,
        {% if output.json == true %}
          "serverSide": true,
          "ajax": {
          "url": '{{ path('json', { 'fileName': output.fileName, 'length': output.page.pagelength|default(10), 'start':output.page.pagination|default(0)  }) }}',
          "data": { }
            },
        {% else %}
          "data":{{ output.data|raw }},
        {% endif %}
   });
});

Because the source code of my main page is now full of javascript I try to move it into an external file, to have a more clean appearance:因为我的主页的源代码现在充满了 javascript 我尝试将其移动到外部文件中,以获得更干净的外观:

<script src="{{ absolute_url(asset('js/script.js')) }}"></script>

But it does not work because I have so much twig variables, and they are not recognized anymore.但它不起作用,因为我有这么多 twig 变量,它们不再被识别。

For every twig variable I get an error message, like this for example:对于每个 twig 变量,我都会收到一条错误消息,例如:

SyntaxError: expected property name, got '{'

First of all (as the comments already said) it is not a good idea to mix JavaScript with Twig.首先(正如评论已经说过的),将 JavaScript 与 Twig 混合不是一个好主意。

  • Makes your code hard to maintain, hard to read and hard to understand使您的代码难以维护、难以阅读和难以理解
  • Syntax errors and JavaScript errors might happen quite easily语法错误和 JavaScript 错误可能很容易发生
  • Probably messes up syntax highlighting in IDEs可能会弄乱 IDE 中的语法高亮显示
  • etc.等等

How to improve this situation?如何改善这种情况? Obviously you have the variable output.显然你有变量 output。 You might do the following in your main file:您可以在主文件中执行以下操作:

var output = {{ output|json_encode() }};

Within script.js you might do something like:在 script.js 中,您可能会执行以下操作:

$(document).ready(function () {

 let options = { "repsonsive": true };

 if(output.json === true) {
   options.serverSide = true;
   options.ajax = { ... }
 } else {
   options.data = output.data
 }
  var table = $('.datatable').DataTable(options);
});

Use this process of refactoring also to clean and restructure your code and especially keep JavaScript and CSS seperated from the Twig files as good as possible.使用此重构过程也可以清理和重构您的代码,尤其是尽可能将 JavaScript 和 CSS 与 Twig 文件分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM