Created
October 20, 2020 23:50
-
-
Save arthurlauck/1dc9c0815e9245f1967de951290597c3 to your computer and use it in GitHub Desktop.
symfony render script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% block javascripts %} | |
<script> | |
{{ render_scripts() }} | |
</script> | |
{% endblock %} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% block form_block_widget %} | |
{{ add_script("console.log('this is the script');") }} | |
{% endblock %} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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