【问题标题】:How to use translation __() with hyperlinks如何使用带有超链接的翻译 __()
【发布时间】:2021-11-19 17:47:12
【问题描述】:

在 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 的等效操作?

【问题讨论】:

    标签: javascript php reactjs wordpress jsx


    【解决方案1】:

    您正在尝试使用 React 在翻译后的句子中插入 html 标签。您需要保留一个占位符(例如{0}),然后您需要将其替换为实际组件。

    当您使用 PHP 时,您只是用其他文本(即您的 HTML)替换文本,因此您正在使用组件,因此您不能简单地替换它们。

    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.`(用于字符串模板)。

    【讨论】:

      【解决方案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>
      
          )
      }
      

      Similar Question

      【讨论】:

        【解决方案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>
            )
        }
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-02-02
          • 2016-06-18
          • 2019-11-11
          • 1970-01-01
          • 1970-01-01
          • 2017-01-16
          • 2012-01-09
          相关资源
          最近更新 更多