Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Created May 25, 2021 08:26
Show Gist options
  • Save bartwttewaall/e3a522faf4ddb762ca599a32afafd711 to your computer and use it in GitHub Desktop.
Save bartwttewaall/e3a522faf4ddb762ca599a32afafd711 to your computer and use it in GitHub Desktop.
Use Twig/Craft pre-translated strings in Vue components
/**
* translate(dictionary, key, params)
*
* Used to bridge twig translations into Vue files where we want to use the pre-translated values of keys in the vue component's template
@example
props: {
labels: { type: String }
},
setup() {
const state = reactive({
labels: {}
});
onMounted(() => {
if (props.labels) state.labels = JSON.parse(props.labels || '') as { [key: string]: string };
});
function t(key: string, params?: { [key: string]: string }) {
return translate(state.labels, key, params);
}
return { t };
}
{# In the Twig template you can now create an object containing the translated keys as such: #}
{% set dictionary = {
cancel: 'cancel'|t,
ok: 'ok'|t
} %}
<my-component
labels="{{ dictionary|json_encode }}">
</my-component>
*/
export function translate(dictionary: { [key: string]: string }, key: string, params?: { [key: string]: string }) {
const value = key in dictionary ? dictionary[key] : '';
if (params)
return Object.entries(params).reduce((prev, current) => {
const [k, v] = current;
return prev.replace(`{${k}}`, v);
}, value);
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment