【问题标题】:How to get twig data for a JS script如何获取 JS 脚本的树枝数据
【发布时间】:2022-01-08 13:37:24
【问题描述】:

我正在尝试获取 JS 脚本的数据,该脚本是显示 Folder 对象中包含的数据的模式

我创建了一个controller 以在树枝视图中显示Folder 对象

在我的twig view 中,我可以毫无问题地在我的twig view 中列出Folder 的每个子元素(实体):
bars, bars, quxes (板、类别、元素)

Folder 对象显示为带有子元素选项卡的卡片 html:
bars, bars, quxes (板、类别、元素)

在标签Boards 我有一个for loop 显示包含的元素

如果我选择其中一个元素,我会打开一个显示
namedescription 的模式

问题就在这里:

如何在 Js 中构建:
Boardname 的变量:barname
另一个是descriptionbardescription
在我的模态中阅读。

我已经创建了一个树枝服务“menubar”来访问数据
我从显示 Folders (foo)
的侧边栏菜单中使用 显示选定的文件夹

控制器

    #[Route('/folder', name: 'folder_')]
class FooController extends AbstractController
{
    #[Route('/{id}/show', name: 'show', methods: 'GET')]
    public function show(Foo $foo): Response
    {
        return $this->render('foo/show.html.twig', [
            'foo' => $foo,
        ]);
    }
}

显示包含元素的选定文件夹: Boards => Categories => Elements 按选项卡

Twig 标签板

<div class="tab-pane fade" id="pills-boards" role="tabpanel" aria-labelledby="pills-boards-tab">
    <p>
        {% for bar in foo.bars %}

    <p><button type="button" class="alert_demo_2 btn btn-secondary" id="">  {{bar}} </button></p>

        {% endfor %}

    </p>
</div>

按钮标签板通过 javascript 调用 Modal,其中必须包含字段: 姓名 和 描述 董事会

Js

<script>

var barname = '{{  }}';
var bardescription = '{{  }}';

  //== Class definition
  var SweetAlert2Demo = function() {

    //== Demo
    var initDemos = function() {

      //== Sweetalert Demo 2
      $('.alert_demo_2').click(function(e) {
        swal(barname, bardescription, {
          buttons: {
            confirm: {
              className : 'btn btn-success'
            }
          }
        });
      });

    return {
      //== Init
      init: function() {
        initDemos();
      }
    };
  }();

  //== Class Initialization
  jQuery(document).ready(function() {
    SweetAlert2Demo.init();
  });
</script>

var barnamebardescription 是显示预期数据所需的 twig 兼容变量: 名称、描述

Modal 将显示在显示的所选文件夹

中找到的Boards列表

实体 Foo(文件夹)

<?php

declare(strict_types=1);

namespace App\Entity;

use App\Repository\FooRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
* @ORM\Entity(repositoryClass=FooRepository::class)
*/
class Foo
{
   /**
    * @ORM\Id
    * @ORM\GeneratedValue
    * @ORM\Column(type="integer")
    */
   private ?int $id = null;

   /**
    * @ORM\Column(type="string", length=255)
    */
   #[Assert\NotBlank]
   private string $name;

   /**
    * @ORM\Column(type="text", nullable=true)
    */
   private $description;

   /**
    * @var Collection<int, Bar>
    * @ORM\OneToMany(targetEntity=Bar::class, mappedBy="foo", orphanRemoval=true, cascade={"persist"})
    */
//    #[Assert\Count(min: 1)]
   #[Assert\Valid]
   private Collection $bars;

   public function __construct()
   {
       $this->bars = new ArrayCollection();
   }

   public function __toString()
   {
       return $this->name;
   }

   public function getId(): ?int
   {
       return $this->id;
   }

   public function getName(): ?string
   {
       return $this->name;
   }

   public function setName(string $name): self
   {
       $this->name = $name;

       return $this;
   }

   public function getDescription(): ?string
   {
       return $this->description;
   }

   public function setDescription(?string $description): self
   {
       $this->description = $description;

       return $this;
   }

   /**
    * @return Collection<int, Bar>
    */
   public function getBars(): Collection
   {
       return $this->bars;
   }

   public function addBar(Bar $bar): self
   {
       if (!$this->bars->contains($bar)) {
           $this->bars->add($bar);
           $bar->setFoo($this);
       }

       return $this;
   }

   public function removeBar(Bar $bar): self
   {
       if ($this->bars->removeElement($bar)) {
           if ($bar->getFoo() === $this) {
               $bar->setFoo(null);
           }
       }

       return $this;
   }
}

实体栏(板)

<?php

declare(strict_types=1);

namespace App\Entity;

use App\Repository\BarRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
* @ORM\Entity(repositoryClass=BarRepository::class)
*/
class Bar
{
   /**
    * @ORM\Id
    * @ORM\GeneratedValue
    * @ORM\Column(type="integer")
    */
   private ?int $id = null;

   /**
    * @ORM\Column(type="string", length=255)
    */
   #[Assert\NotBlank]
   #[Assert\Length(min: 2)]
   private string $name;

   /**
    * @ORM\Column(type="text", nullable=true)
    */
   private $description;

   /**
    * @ORM\ManyToOne(targetEntity=Foo::class, inversedBy="bars")
    * @ORM\JoinColumn(nullable=false, onDelete="CASCADE")
    */
   private ?Foo $foo = null;

   /**
    * @var Collection<int, Baz>
    * @ORM\OneToMany(targetEntity=Baz::class, mappedBy="bar", orphanRemoval=true, cascade={"persist"})
    */
//    #[Assert\Count(min: 1)]
   #[Assert\Valid]
   private Collection $bazs;

   public function __construct()
   {
       $this->bazs = new ArrayCollection();
   }

   public function __toString()
   {
       return $this->name;
   }

   public function getId(): ?int
   {
       return $this->id;
   }

   public function getName(): ?string
   {
       return $this->name;
   }

   public function setName(string $name): self
   {
       $this->name = $name;

       return $this;
   }

   public function getFoo(): ?Foo
   {
       return $this->foo;
   }

   public function setFoo(?Foo $foo): self
   {
       $this->foo = $foo;

       return $this;
   }

   public function getDescription(): ?string
   {
       return $this->description;
   }

   public function setDescription(?string $description): self
   {
       $this->description = $description;

       return $this;
   }

   /**
    * @return Collection<int, Baz>
    */
   public function getBazs(): Collection
   {
       return $this->bazs;
   }

   public function addBaz(Baz $baz): self
   {
       if (!$this->bazs->contains($baz)) {
           $this->bazs->add($baz);
           $baz->setBar($this);
       }

       return $this;
   }

   public function removeBaz(Baz $baz): self
   {
       if ($this->bazs->removeElement($baz)) {
           // set the owning side to null (unless already changed)
           if ($baz->getBar() === $this) {
               $baz->setBar(null);
           }
       }

       return $this;
   }
}

转储

array:3 [▼
  "foo" => App\Entity\Foo {#382 ▼
    -id: 96
    -name: "Design"
    -description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostru ▶"
    -bars: Doctrine\ORM\PersistentCollection {#385 ▼
      -snapshot: []
      -owner: App\Entity\Foo {#382}
      -association: array:15 [ …15]
      -em: Doctrine\ORM\EntityManager {#246 …11}
      -backRefFieldName: "foo"
      -typeClass: Doctrine\ORM\Mapping\ClassMetadata {#360 …}
      -isDirty: false
      #collection: Doctrine\Common\Collections\ArrayCollection {#386 ▼
        -elements: []
      }
      #initialized: false
    }
  }
  "app" => Symfony\Bridge\Twig\AppVariable {#354 ▶}
  "menubar" => App\Twig\BarsExtension {#342 ▶}

【问题讨论】:

  • 这个JS脚本是在另一个文件里还是你说的是twig文件里的JS脚本?
  • 只有这部分在 twig var barname = '{{ }}'; var bardescription = '{{ }}'; 这部分是从 base.html.twig 的底部调用的:$('.alert_demo_2').click(function(e) { swal(barname, bardescription, { buttons: { confirm: { className : 'btn btn-success' } } }); });
  • 这项工作但仅适用于索引 [0] 元素:var barname = ['{{ foo.bars[0].name }}']; var bardescription = ['{{ foo.bars[0].description }}']; 我需要一个循环..
  • 是的,根据您在Foo 实体中的注释,它与Bar 实体具有OneToMany 关系。因此,当您访问 foo.bars 时,它会返回一个 Bar 实体数组。
  • 这能回答你的问题吗? Twig variable in external JS file

标签: javascript symfony doctrine-orm twig


【解决方案1】:

正如我标记为欺骗的链接问题中所见,您可以借助data-* 属性将数据从树枝传递到javascript。将您的模板更改为以下内容

<div class="tab-pane fade" id="pills-boards" role="tabpanel" aria-labelledby="pills-boards-tab">
{% for bar in foo.bars %}
    <button type="button" class="alert_demo_2 btn btn-secondary" data-name="{{ bar.getName() }}" data-description="{{ bar.getDescription() }}">{{ bar.getName() }}</button>
{% endfor %}
</div>

通过添加这些属性,您现在可以在 javascript 中使用它们

$(document).on('click', '.alert_demo_2', function(e) {
    swal($(this).data('name'), $(this).data('description'), {
        buttons: {
            confirm: {
                className : 'btn btn-success'
            }
        }
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 2014-11-20
    • 1970-01-01
    • 2019-09-02
    • 2016-09-02
    相关资源
    最近更新 更多