块编辑器中的多行通知

时间:2021-09-09 作者:Borje

页面https://developer.wordpress.org/block-editor/how-to-guides/notices/ 具有以下代码,用于将通知添加到块编辑器:

( function ( wp ) {
    wp.data.dispatch( \'core/notices\' ).createNotice(
        \'success\', // Can be one of: success, info, warning, error.
        \'Post published.\', // Text string to display.
        {
            isDismissible: true, // Whether the user can dismiss the notice.
            // Any actions the user can perform.
            actions: [
                {
                    url: \'#\',
                    label: \'View post\',
                },
            ],
        }
    );
} )( window.wp );
这对我来说很好,我可以很好地显示我的消息。但我想显示一条包含多行的消息,我选择了换行符的位置。

我试过了Post <br /> published, Post \\n published, Post \\r\\n published 但没有任何内容在单独的行上显示这些单词。

在上找不到任何选项https://developer.wordpress.org/block-editor/reference-guides/data/data-core-notices/ 这对我也有帮助。

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

The 3rd parameter for the function accepts a private option named __unstableHTML which if true, then enables HTML in the notice message/content:

createNotice(
    \'success\',
    \'Post published.<br /> Line 2. Should work in WordPress 5.8.\',
    {
        __unstableHTML: true, // true = allows HTML; default false
        isDismissible: true,
        actions: [ ... ],
    }
)

However, in the option\'s description (see wp-includes/js/dist/notices.js, lines 408-412):

/**
 * @typedef {Object} WPNotice Notice object.
 *
 * ...
 * @property {string}  content          Notice message.
 * ...
 * @property {string}  __unstableHTML   Notice message as raw HTML. Intended to
 *                                      serve primarily for compatibility of
 *                                      server-rendered notices, and SHOULD NOT
 *                                      be used for notices. It is subject to
 *                                      removal without notice.
 * ...
 *
 */

So use the option at your very own risks..

And I\'m afraid, apart from using that option, there doesn\'t seem to be any other ways to make the new lines work in notice messages rendered via createNotice(). There\'s the white-space: pre-wrap trick in CSS, but unfortunately, from what I could tell, \\n (and its Unicode version — \\u000a) are stripped from the notice message. :(