如何在AlpineJS中使用Yii的Yii::t()翻译“Article(s)”?
解决AlpineJS中无法使用Yii框架翻译标签的问题
问题核心:AlpineJS是前端运行的JS代码,Yii::t()是后端PHP渲染方法,直接在JS模板字符串中混写会破坏JS语法结构,导致解析报错。
解决方案一:提前定义全局翻译变量
在页面的PHP视图中,先通过PHP渲染好翻译文本,存入全局JS变量:
<script> // 定义全局翻译对象 const appTranslations = { articlesLabel: '<?= Yii::t('app', 'Article(s)') ?>', filteredLabel: '<?= Yii::t('app', 'Filtered') ?>' }; </script>
然后在AlpineJS代码中直接引用该变量:
get articleCount() { if (this.blog.articles.length === this.blogArticle.length) { return `${this.blog.articles.length} ${appTranslations.articlesLabel}`; } return `${this.course.topics.length} ${appTranslations.articlesLabel}, ${this.blogArticle.length} ${appTranslations.filteredLabel}`; }
解决方案二:使用Yii的registerJs注入翻译内容
如果在Yii控制器或视图类中,可通过registerJs方法将翻译内容注入页面:
<?php $this->registerJs( "window.appTranslations = { articlesLabel: '".Yii::t('app', 'Article(s)')."', filteredLabel: '".Yii::t('app', 'Filtered')."' };", \yii\web\View::POS_HEAD ); ?>
之后在AlpineJS代码里同样使用window.appTranslations.articlesLabel和window.appTranslations.filteredLabel即可。
原写法错误原因
原代码中${this.blog.articles.length <?=Yii::t('app', 'Article(s)')?> }会被PHP渲染成类似${10 Article(s)}的内容,不符合JS模板字符串语法规则,直接导致JS解析报错。
内容的提问来源于stack exchange,提问作者chiper4
相关产品推荐
相关产品推荐

