Alex
Alex

Reputation: 35008

How to access a translation in Javascript of the Shopware 6 store front?

How can a translations snipped (created like here: https://developer.shopware.com/docs/guides/plugins/plugins/storefront/add-translations) be accessed in Javascript code of the frontend?

What first comes to my mind is to print the translated string into some kind of hidden tag / data attribute within the twig file and then read it from the JavaScript code.

But is there a suggested way to do this?

EDIT: I am looking for examples on how the Shopware 6 core developers do this, to find a best-practice and not invent something own.

Upvotes: 3

Views: 1647

Answers (1)

tinect
tinect

Reputation: 501

If you need it once a page, you can add it into data-attribute within plugin-related element. Other way, especually recommended when you need it multiple time on an page to save content:

I personally like set these texts in a variable for the window. Just where other window-variable are set and request them within the plugin.

{% block base_script_router %}
{{ parent() }}
<script>
    window.contactTexts = {
        product: '{{ 'anySnippet'|trans|e('js') }}',
        basket: '{{ 'anySnippet'|trans|e('js') }}',
        order: '{{ 'anySnippet'|trans|e('js') }}',
        inkl: '{{ 'anySnippet'|trans|e('js') }}'
    };
</script>
{% endblock %}

Upvotes: 5

Related Questions