Search code examples
javascriptsymfonytwigbolt-cms

Javascript variable to Twig


I need to create a hash and put it in the placeholder for html input. I need the hash from the makehash() function in the placeholder. I have tried to achieve this with the following code segment but am not getting the desired results.

placeholder: "string";

{% block javascript %}
    <script>
        function makehash() {
          var hash = "";
          var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

          for (var i = 0; i < 5; i++)
            hash += possible.charAt(Math.floor(Math.random() * possible.length));

          return hash;
        }
    </script>
{% endblock %}

{% set attributes = {
    guuid: {
        class:           option.class,
        data_errortext:  option.errortext,
        id:              key,
        maxlength:       225,
        name:            name,
        pattern:         (option.pattern and option.pattern not in ['url', 'email']) ? option.pattern : '',
        placeholder:     hash should come here,
        readonly:        option.readonly,
        required:        option.required,
        title:           option.title,
        type:            (option.pattern in ['url', 'email']) ? option.pattern : 'text',
        value:           context.content.get(contentkey)|default(''),
    }
} %}

Solution

  • You can't do what you want.

    You site is rendered as followed:

    1. client requests page
    2. server receives request and sends it to php
    3. php fires up symfony
    4. symfony fires up twig
    5. twig returns content to symfony
    6. symfony returns content to php
    7. php gives content to webserver
    8. webserver gives content to client
    9. clients browser interprets html
    10. clients browser executes javascript

    The distance between step 4 an 10 is separated by computers(server computer and client computer). They simply don't know about eachother.

    For twig the javascript code is simply text.
    For javascript the twig code doesn't exist. Only the rendered html.

    Now if you want to use GUID's I suggest you use something like https://github.com/webpatser/laravel-uuid