如何使用PHPDoc内联JavaScript字符串参数以允许在PhpStorm中突出显示语法

时间:2018-04-10 09:23:45

标签: php phpstorm phpdoc

WordPress有一个PHP函数,可以向页面注入内联JavaScript:https://developer.wordpress.org/reference/functions/wp_add_inline_script/

有没有办法标记$data参数,告诉IDE它是一个包含JavaScript代码的字符串,然后语法突出显示它?

wp_add_inline_script( 'xyz', 'new xyz();' );


/**
 * Adds extra code to a registered script.
 *
 * @param string $handle   Name of the script to add the inline script to.
 * @param string $data     String containing the javascript to be added.
 * @param string $position Optional. Whether to add the inline script before the handle
 *                         or after. Default 'after'.
 * @return bool True on success, false on failure.
 */
function wp_add_inline_script( $handle, $data, $position = 'after' ) {
    _wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );

    if ( false !== stripos( $data, '</script>' ) ) {
        _doing_it_wrong( __FUNCTION__, sprintf(
            /* translators: 1: <script>, 2: wp_add_inline_script() */
            __( 'Do not pass %1$s tags to %2$s.' ),
            '<code>&lt;script&gt;</code>',
            '<code>wp_add_inline_script()</code>'
        ), '4.5.0' );
        $data = trim( preg_replace( '#<script[^>]*>(.*)</script>#is', '$1', $data ) );
    }

    return wp_scripts()->add_inline_script( $handle, $data, $position );
}

1 个答案:

答案 0 :(得分:1)

请参阅Using Language Injections文档页面。

基本上,有三种方法可以做到这一点:

  1. 将光标放在包含JS的字符串中,点击Alt+Enter(或点击灯泡),选择Inject language or reference然后选择JS。
  2. 定义变量并在其上添加// language=JavaScript,然后将其传递给方法:

    // language=JavaScript
    $data = 'document.getElementbyId("selector")';
    
    wp_add_inline_script('handle', $data, 'position');
    
  3. 在您的情况下,可能是最合适的解决方案,在传递参数之前使用/* language=JavaScript */

    wp_add_inline_script('handle', /* language=JavaScript */ 'document.getElementbyId("selector")', 'position');