提问人:micky 提问时间:9/27/2021 最后编辑:micky 更新时间:10/25/2021 访问量:997
如何使用带有超链接的翻译 __()
How to use translation __() with hyperlinks
问:
在 WordPress 中创建块时,我需要添加一个带有链接的翻译。我在 JS 中这样做,但它没有提供预期的结果:
import { render } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
export default function Final() {
let d = <a href="https://example.com">bothered me.</a>;
return (
<p> { __( 'The cold never {d} anyway.', 'text-domain' ) } </p>
)
}
document.addEventListener( "DOMContentLoaded", function(event) {
const appRoot = document.getElementById( 'root' );
if ( appRoot ) {
render(
<Final/>,
appRoot
)
}
});
在 PHP 中,我可以轻松地使用 sprintf 并使用像 %1s 这样的占位符来做到这一点。
echo sprintf(
__( 'The cold never %1s anyway', 'text-domain' ),
'<a href="https://example.com">bothered me.</a>'
);
在 react 中创建块时,如何做相当于 sprintf 的操作?
答:
3赞
Newbie
9/28/2021
#1
您正在尝试使用 React 在翻译的句子中插入 html 标签。您需要保留一个占位符(类似于 ),然后您需要将其替换为实际组件。{0}
当使用PHP时,你只是用其他文本(即你的HTML)替换文本,在react中,你使用的是组件,所以你不能简单地替换它们。
export default function Final() {
const [before, after] = __('The cold never {0} anyway.', 'text-domain').split('{0}');
return (<p>
{ before }
<a href="https://example.com">bothered me.</a>
{ after }
</p>);
}
旁注
这是一个普通的字符串,也许是你想要的(用于字符串模板)。'The cold never {d} anyway.'
`The cold never ${d} anyway.`
1赞
Dmitry Leiko
10/6/2021
#2
尝试使用模板字符串(ES6):
export default function Final() {
let d = <a href="https://example.com">bothered me.</a>;
return (
<p> { __( `The cold never ${d} anyway.`, 'text-domain' ) } </p>
)
}
1赞
emptyhua
10/25/2021
#3
另一种方法是使用内置的sprintf
@wordpress/i18n
import { render } from '@wordpress/element';
import { sprintf, __ } from '@wordpress/i18n';
export default function Final() {
let d = '<a href="https://example.com">bothered me.</a>';
let txt = sprintf(__('The cold never %1s anyway.', 'text-domain'), d);
return (
<p dangerouslySetInnerHTML={{__html: txt }}></p>
)
}
评论