esc_html_x()
云策文档标注
概述
esc_html_x() 是一个 WordPress 函数,用于在翻译字符串时提供上下文信息,并转义输出以确保 HTML 安全。它结合了翻译和转义功能,适用于需要国际化和安全输出的场景。
关键要点
- 函数 esc_html_x() 接受三个参数:$text(要翻译的文本)、$context(翻译上下文)和 $domain(文本域,默认为 'default')。
- 如果翻译不存在或文本域未加载,函数会转义原始文本并返回。
- 返回值为转义后的翻译字符串,可直接用于 HTML 输出。
- 内部实现基于 translate_with_gettext_context() 和 esc_html() 函数。
- 与 _e 函数不同,esc_html_x() 不自动输出,需要显式使用 echo 或类似方式。
- 自 WordPress 2.9.0 版本引入。
代码示例
function esc_html_x( $text, $context, $domain = 'default' ) {
return esc_html( translate_with_gettext_context( $text, $context, $domain ) );
}注意事项
- 使用 _x 函数时,需注意与 _e 函数的区别:_e 函数自动输出,而 _x 函数不输出,需要手动处理。
- 上下文参数 $context 有助于翻译者理解文本的具体使用场景,特别是对于多义词。
- 确保文本域 $domain 正确设置,以加载相应的翻译文件。
原文内容
Translates string with gettext context, and escapes it for safe use in HTML output.
Description
If there is no translation, or the text domain isn’t loaded, the original text is escaped and returned.
Parameters
$textstringrequired-
Text to translate.
$contextstringrequired-
Context information for the translators.
$domainstringoptional-
Text domain. Unique identifier for retrieving translated strings.
Default'default'.
Source
function esc_html_x( $text, $context, $domain = 'default' ) {
return esc_html( translate_with_gettext_context( $text, $context, $domain ) );
}
Changelog
| Version | Description |
|---|---|
| 2.9.0 | Introduced. |
Skip to note 2 content
Abdul Hadi
The _x functions (like esc_html_x) are essentially the same as their _e counterparts, with an added “context” argument to explain the context a word or phrase is used in. Useful for words with multiple meanings:
<!-- Here, we're asking the user to comment (verb): --> <a href="#comment"> </a> <!-- Here, we're simply adding a heading with the text "Comment" (noun) --> <h3> </h3>