Skip to content

Instantly share code, notes, and snippets.

@arthurlauck
Created October 20, 2020 23:50
Show Gist options
  • Save arthurlauck/1dc9c0815e9245f1967de951290597c3 to your computer and use it in GitHub Desktop.
Save arthurlauck/1dc9c0815e9245f1967de951290597c3 to your computer and use it in GitHub Desktop.
symfony render script
{% block javascripts %}
<script>
{{ render_scripts() }}
</script>
{% endblock %}
{% block form_block_widget %}
{{ add_script("console.log('this is the script');") }}
{% endblock %}
<?php
// this is twig filter
namespace App\Twig\Filters;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class Javascript extends AbstractExtension
{
private array $scripts = [];
public function getFunctions()
{
return [
new TwigFunction('add_script', [$this, 'add_script']),
new TwigFunction('render_scripts', [$this, 'renderScripts'], ['is_safe' => ['html']]),
];
}
public function add_script(string $script): void
{
$this->scripts[] = $script;
}
public function renderScripts()
{
$output = '';
if (empty($this->scripts)) {
return $output;
}
foreach ($this->scripts as $script) {
$output .= $script;
}
return $output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment