diff --git a/.gitignore b/.gitignore index 90157b1..c12a8a1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /node_modules -.DS_Store \ No newline at end of file +.DS_Store +example/node_modules diff --git a/README.md b/README.md index e63e66a..4f18d2d 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ var myComp = Vue.extend({ {{ t('Hello World') }} How are you? `, - + mounted() { // Define what language you want to use. // This can be called in something like a header with a language selector menu @@ -46,9 +46,9 @@ var myComp = Vue.extend({ var vm = new Vue({ el: '#app', - + components: {myComp}, - + template: `
` @@ -119,6 +119,25 @@ this.$translate.$on('language:changed', language => { }) ``` +### Parameters + +You can use the method `textWithParams` if you would like to insert parameters in your translation strings. + +```js +this.$translate.textWithParams('translation.string', { + keyA: 'Glenn', + keyB: 'John' +}) + +{{ tWithParams('translation.string', { keyA: 'Glenn', keyB: 'John' }) }} + +// In locales.js +'translation.string': 'My name is %keyA%. My brother is named %keyB%.' + +// Result +'My name is Glenn. My brother is named John.' +``` + ##### language:init When the first language is set. @@ -129,4 +148,4 @@ When the language to use was changed from the previous value. Everytime a language is changed, either is the first time or not. ##### locales:loaded -When locales are loaded either by any of the 3 options \ No newline at end of file +When locales are loaded either by any of the 3 options diff --git a/src/vue-translate.js b/src/vue-translate.js index 00a83d2..210c7d4 100644 --- a/src/vue-translate.js +++ b/src/vue-translate.js @@ -73,6 +73,22 @@ const VueTranslate = { } return this.locale[t]; + }, + + textWithParams(t, params = null) { + if (!this.locale || !this.locale[t]) { + return t; + } + + if (!this.params || this.params === null || typeof this.params === 'undefined') { + return t; + } + + Object.keys(params).forEach((key) => { + t = t.replace(`%${key}%`, params[key]); + }); + + return t; } } }); @@ -90,6 +106,10 @@ const VueTranslate = { // An alias for the .$translate.text method t(t) { return this.$translate.text(t); + }, + + tWithParams(t, params) { + return this.$translate.text(t, params); } },