Open
Conversation
- 修改了 `GetText::translate` 和 `GetText::ngettext`,在启用缓存时显式设置 `$num`。 - 确保未找到翻译时 `$num` 设置为 `-1`,使 `GetTextMulti` 能够继续搜索后续文件。
- 修改了 `I18n::addLang`,在添加翻译文件时自动调用 `init()`。 - 确保初始化后再调用 `addFile`,避免抛出异常。
joyqi
requested changes
Mar 5, 2025
Member
There was a problem hiding this comment.
这一个有待商榷,其实我预想中更好的做法是不需要手动添加语言文件,只需要把语言文件放置在对应的目录就会自动加载。之前的实现比较粗糙。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
该 Pull Request 旨在解决 I18n 实现中的两个关键问题:
多语言文件加载问题
当前实现中,
GetTextMulti::translate遍历所有语言文件的 handler,期望通过$count判断是否找到翻译。若$count != -1则终止循环,否则继续检查后续文件。而不论是被标记短路 (
short_circuit) 或是启用缓存 (enable_cache) 的情况下,GetText::translate和GetText::ngettext方法都未正确设置$num的值,导致GetTextMulti在遍历翻译文件时提前终止。修改后,在这两个条件中
$num会被显式设置为-1(未找到)或0(找到),确保能够通过$count判断是否找到翻译,使得所有翻译文件都能被正确遍历。翻译文件加载时机问题
在加载主题的
function.php时,I18n可能尚未初始化,而I18n::init是私有方法,无法直接调用。针对此问题参考了I18n::translate和I18n::ngettext的实现,对I18n::addLang进行了修改。修改后,在
I18n::addLang中会尝试自动调用init(),并且再确认在未能载入的情况下不进一步尝试调用GetTextMulti::addFile。修改后,对于主题或是插件的开发者,都可以经由下列方法实现 I18n(以主题为例):
通过
\Typecho\I18n::addLang在主题的
function.php中,可以通过:获取到当前挂载的语言文件,如果其值存在则证明用户的语言设置为了
zh_CN之外的值,那么就可以通过basename进一步获取到形如en_US.mo的内容,开发者可以自行判断是否存在相应的 I18n 支持,并且通过:这样的方法进行挂载。
通过
\Utils\Helper::lang该方法会自行寻找
<theme_folder>/lang目录下是否存在用户所选语言的.mo文件并进行挂载。