在外部JS文件中使用TWIG变量



我正在为我的Symfony Project设置WebPack,我想拥有特定页面的JavaScript文件。我需要在我将在WebPack中构建的外部JS文件中使用诸如{{ form.licenseText.vars.id }}之类的树枝过滤器。这里有帮助吗?

我尝试设置变量和调用标签之后似乎不起作用。

$(document).ready(function(){
  $.trumbowyg.svgPath = '/img/trumbowyg-icons.svg';
  var trumbowyg_config = {
    btns: [
      ['formatting'],
      'btnGrp-semantic',
      ['link'],
      ['insertImage'],
      'btnGrp-lists',
      ['horizontalRule'],
      ['removeformat'],
      ['viewHTML'],
      ['fullscreen']
    ]
  };
  $('#{{ form.descriptionText.vars.id }}').trumbowyg(trumbowyg_config);
  $('#{{ form.licenseText.vars.id }}').trumbowyg(trumbowyg_config);
  /* toggle text boxes in respect to the auto update settings */
  $('#{{ form.descriptionTextAutoUpdate.vars.id }}').on('change', function() {
    var au = $('input[name="{{ form.descriptionTextAutoUpdate.vars.full_name }}"]:checked').val() == '1';
    var el = $('#descriptionText_div');
    au ? el.hide() : el.show();
  });
  $('#{{ form.licenseTextAutoUpdate.vars.id }}').on('change', function() {
    var au = $('input[name="{{ form.licenseTextAutoUpdate.vars.full_name }}"]:checked').val() == '1';
    var el = $('#licenseText_div');
    au ? el.hide() : el.show();
  });

我想在我的外部JS文件中访问这些树枝变量,如上所述。

您可以为此使用两个技巧。

a。在您的表单元素中使用类或特定属性,并使用全局选择器访问它们。

<?php
namespace AppForm;
class MyForm extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
       $builder->add("descriptionText", null, [
           "attr" => [ "class" => ["trumbowygable"]],
           ...
       ]) ;
       ... or ...
       $builder->add("otherField", null, [
           "attr" => [ "data-other-thing" => 1]],
           ...
       ]) 

  }
}

和JS看起来像...

$('input.trumbowygable').trumbowyg(trumbowyg_config);
// or
$('input[data-other-thing]').on("someEvent", bla bla bla);

b。创建一个通过参数接收ID元素的全局JavaScript函数。

function buildTrumbowyg(id_one, id_two) {
    $('#' + id_one).blaBlaBla( ... )
}

您可以使用幽灵输入(未显示(添加变量,您想要的值类似:

<input type="text" name="your_variable_name" id="your_variable_id" value="{{ your_variable }}" style="display: none;">

在您的外部JavaScript中呼叫之后,例如:

$(document).ready(function(){
/********/
let variable = $("#your_variable_id").val();
/*********/
});

最新更新