Browse Source

add custom plugin to separate site content strings from templates

axolotle 3 years ago
parent
commit
fb0c99e444
3 changed files with 48 additions and 2 deletions
  1. 3 2
      src/main.js
  2. 10 0
      src/messages/fr.json
  3. 35 0
      src/messages/index.js

+ 3 - 2
src/main.js

@@ -2,11 +2,11 @@ import Vue from 'vue'
 import BootstrapVue from 'bootstrap-vue'
 import Meta from 'vue-meta'
 import Vue2TouchEvents from 'vue2-touch-events'
+import VueMessages from './messages'
+import App from './App'
 import router from './router'
 import store from './store'
 
-import App from './App'
-
 
 Vue.use(BootstrapVue, {
   BButton: { pill: true },
@@ -15,6 +15,7 @@ Vue.use(BootstrapVue, {
 })
 Vue.use(Meta)
 Vue.use(Vue2TouchEvents)
+Vue.use(VueMessages)
 
 
 // Register global components

+ 10 - 0
src/messages/fr.json

@@ -0,0 +1,10 @@
+{
+  "title": "En françaiS au pluriel",
+  "sections": {
+    "home": "Accueil",
+    "library": "Bibliothèque",
+    "kit": "Kit de désapprentissage",
+    "gallery": "Créations numériques"
+  },
+  "bounce_texts": "Textes rebonds"
+}

+ 35 - 0
src/messages/index.js

@@ -0,0 +1,35 @@
+import messages from './fr.json'
+
+
+function getMessage (keyedPath, alt) {
+  console.log(keyedPath, alt)
+  let message
+  try {
+    message = keyedPath.split('.').reduce((parent, key) => {
+      return parent[key]
+    }, messages)
+  } catch {
+    // Silence errors like accessing a key on `undefined`.
+  }
+  return message === undefined
+    ? alt === undefined ? keyedPath : alt
+    : message
+}
+
+
+/*
+ * Allows separtion of static text content from its templates.
+ */
+export default class VueMessages {
+  static install (Vue) {
+    // Adds `this.$t('path.to.string', 'alt')` to every instances.
+    Vue.prototype.$t = getMessage
+
+    // Adds `v-t="'path.to.string'"` directive to every elements.
+    Vue.directive('t', {
+      bind (el, { value }) {
+        el.textContent = getMessage(value)
+      }
+    })
+  }
+}