首页 > 解决方案 > 是否可以在 Laravel 中自动添加翻译变量?

问题描述

我有一些刀片,其中包括许多这样的上诉:

    <div>{{ __('auth.Example') }}</div>
    <a href='#'>{{ __('xyz.Another One Example') }}</a>
    <span>{{ __('xyz.Example Number Three') }}</span>
    ...

我将文件添加xyz.php到目录。现在我想知道,是否可以使用一些命令或方法,将适当的变量添加到这些文件中以重新填充? 除了准备好的翻译,我不会,但类似的东西将不胜感激:auth.phplang/enlang/pl

xyz.php

return [
...
'Another One Example' => 'Another One Example',
'Example Number Three' => 'Example Number Three',
...
];

授权文件

return [
...
'Example' => 'Example'
...
];

之后,我可以快速更改正确语言的翻译值,但首先我需要在正确的文件中包含正确的变量。现在我正在手动将每个变量复制到正确的文件中,但感觉就像是永恒的......你有什么想法吗,我怎样才能更容易地做到这一点?

标签: phplaravelautomationtranslation

解决方案


我以前写过这样的脚本。我使用下面的函数扫描所有文件并使用正则表达式来检测翻译键。

function findTranslationKeys($grep, $path, $regex)
{
    $keys = [];

    $filenames = glob(base_path() . $path . '/**/**');

    foreach ($filenames as $filename) {
        if (preg_match_all($regex, file_get_contents($filename), $matches)) {
            foreach ($matches[1] as $index => $match) {   
                $keys[$match] = $match;
            }
        }
    }

    return $keys;
}

 $keys = $this->findTranslationKeys( '/resources/views', '/__\(\'([^\']*)\'[^\)]*/s');

您可以加载现有的翻译

 $filePath = base_path() . '/resources/lang/en/' . $file . '.php';

 if (file_exists($filePath)) {
     $existing = require $filePath;
 } else {
     $existing = [];
 }

将任何缺少的翻译添加到文件中,然后将文件写回

$fh = fopen($filePath, 'w');
fwrite($fh, "<?php\n");
fwrite($fh, 'return ' . var_export($existing, true) . ';');
fclose($fh);

推荐阅读