在 drupal 8 中使用表单

Working with forms in drupal 8

我在表单 API 中遇到“#markup”问题。

在 Drupal 7 中,我们可以使用如下所示的“#markup”表单元素:

<?php
$form['test'] = array(
    '#type' => 'markup',
    '#markup' => '<div><script src="http://localhost/drupal7/sites/all/libraries/test.js"></script></div>',
  );
?>
//Here is my custom test.js
(function($) {
    Drupal.behaviors.test = {
        attach: function(context, settings) {
            console.log('testttt');
            document.write('*Hello, there!*');
        }
    };
})(jQuery);

及以上代码将在渲染表单时打印“你好!”。

现在在 Drupal 8 中,我使用下面的代码,但它没有打印任何内容。

<?php
$form['test'] = array(
      '#markup' => '<div><script src="http://localhost/project8/sites/all/libraries/test.js"></script></div>',
    );
?>

那么如何在 Drupal 8 中实现这个功能,它已经在 Drupal 7 中运行了。 在脚本标签下它可以是本地脚本或外部脚本.. 请帮忙...

谢谢

#markup 在 Drupal 8 中仍然有效,但现在它在输出之前被过滤了。正如Render API overview中所述:

#markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (I.e, and are not allowed.) See \Drupal\Component\Utility\Xss::$adminTags for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Aternatively, you can use the render array key #allowed_tags to alter which tags are filtered.

作为替代方案,您可以使用 FormattableMarkup:

'#markup' => new FormattableMarkup('<div><script src="http://localhost/project8/sites/all/libraries/test.js"></script></div>', []),

虽然在这种情况下不推荐。

在 Drupal 8 中,不建议使用“#markup”来附加 javascript 文件。 您可以在自定义模块或主题中定义库并将库附加到表单。该库可以包含多个js和(或)css个文件。

要在您的模块中定义库:

假设您的模块名称是 "my_module",在您的模块文件夹中创建一个文件“my_module.libraries.yml”并指定 js 和 css这样的文件

form-script:
  version: 1.x
  css:
    theme:
      css/form.css: {}
  js:
    js/form.js: {}
    js/form-ajax.js: {}
  dependencies:
    - core/jquery

为了将此库附加到您的表单:

$form['#attached']['library'][] = 'my_module/form-script';

然后清除缓存。 js 和 css 文件将按照您在 libraries.yml 文件中提到的相同顺序加载。 您可以在同一个 "my_module.libraries.yml" 文件中定义多个库。