Wrap string using PHP in alphine

44 Views Asked by At

I have a string that I need to wrapped using Yii tag like Yii::t('app' , 'what_string') because I need this to translate per string in other page. But here, there is a word that place on alphineJs and I cant to wrap it using PHP Yii::t('app' , .. anyone can help me how to wrap something like this?

My code in alphine:

get articleCount() {
        if (this.blog.articles.length === this.blogArticle.length) return `${this.blog.articles.length <?=Yii::t('app', 'Article(s)')?> `
          return `${this.course.topics.length} Article(s), ${this.blogArticle.length} Filtered`
},

Here, I want to wrap 'Article(s)' so I just added but it doesn't work here

1

There are 1 best solutions below

0
shaedrich On

You are mixing client-side (JavaScript/Alpine) and server-side code (PHP/Yii). While this is possible to some extend when sending JS code back from the server via PHP, the same cannot be said about the opposite direction, thus, rendering PHP code inside JS is not possible. You need to send your i18n messages to the client one way or the other.

Solution A

  • Make a route to fetch all translations
  • Create an object (or better, a store)
  • Create a function to retrieve a translation from the object/store

<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.6.5/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/3.13.3/cdn.js" defer></script>
<script>
    document.addEventListener('alpine:init', () => {
        Alpine.store('i18n', {
            async init() {
                this.messages = (await axios.get('data:application/json;charset=utf-8;base64,ew0KICAgICJsb3JlbSI6ICJpcHN1bSB7eyBhIH19IHt7IGIgfX0iLA0KICAgICJkb2xvciI6ICJzaXQiDQp9')).data
            },
 
            messages: {},
 
            message(message, options) {
              if (typeof this.messages[message] === 'undefined') {
                return `translation for "${message}" not found. Try one of: ${Object.keys(this.messages).join(', ')}`;
              }
              return this.messages[message].replace(
                  new RegExp(`\{\{ (${Object.keys(options).join('|')}) \}\}`),
                  (match, p1) => options[p1] ?? null,
              );
            }
        })
    })
</script>

<span x-data x-text="$store.i18n.message('lorem', { a: 42, c: 'gibberish' })">Test</span>
<span x-data x-text="$store.i18n.message('ahmet', { d: 'sun' })">Test</span>

Solution B

  • Create a route to fetch a single translation (or use a websocket)
  • Create a function to retrieve the translation directly from the API
  • It's recommended to cache the response (or put them in a store)

Solution C

  • Create the whole Alpine JS script on your server-side and deliver it with the translation already parsed by Yii before returning it as a response