im trying to pass variables from Twig to a JS File to work with them. No matter what I do the console log is always an empty array. But that array is not empty as the dump shows. What am I doing wrong?
PHP:
$user = $this->getUser();
$markers = $doctrine->getRepository(Marker::class)->findBy(["relatedUser" => $user]);
return $this->render("map/index.html.twig", [
"controller_name" => "MapController",
"title" => "Map",
"markers" => $markers
]);
HTML:
{% block javascripts %}
<script>
var markers = '{{ markers|json_encode }}';
</script>
{{ encore_entry_script_tags('mapLogic') }}
{% endblock %}
Javascript:
document.addEventListener('DOMContentLoaded', () => {
console.log(JSON.parse(window.markers));
});
Web Console:
Dump:
Here is the entire code from my Marker Entity. But it does not implement JsonSerializabe:
<?php
namespace App\Entity;
use App\Repository\MarkerRepository;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: MarkerRepository::class)]
class Marker
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\ManyToOne(inversedBy: 'markers')]
#[ORM\JoinColumn(nullable: false)]
private ?User $relatedUser = null;
#[ORM\Column]
private array $geoData = [];
#[ORM\Column]
private ?\DateTimeImmutable $createdAt = null;
public function getId(): ?int
{
return $this->id;
}
public function getRelatedUser(): ?User
{
return $this->relatedUser;
}
public function setRelatedUser(?User $relatedUser): self
{
$this->relatedUser = $relatedUser;
return $this;
}
public function getGeoData(): array
{
return $this->geoData;
}
public function setGeoData(array $geoData): self
{
$this->geoData = $geoData;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeImmutable $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
}

