尝试在 drupal 8 模块中包含资产(js、img、css)

问题描述 投票:0回答:1

我有一个名为 chess 的 drupal 模块,其中要显示不同的图像、要包含的 javascript 以及要链接的 css。

我尝试定义一个

chess/chess.libraries.yml
,如下所示:

chess:
  version: 1.x
  css:
    theme:
      css/chess.css: {}
  js:
    js/jquery-ui.min.js: {}
    js/jquery.ui-touch-punch.min.js: {}
    js/jquery.simulate.js: {}
    js/chess.js: {}
    js/socket.io.js: {}
    js/chess-socket.js: {}
    js/chat.js: {}
  dependencies:
    - core/jquery

并在

{{ attach_library('chess/chess') }}
中包含一行
chess/templates/index.html.twig
。这些图像位于
chess/images
。此外,我的 ChessController 的渲染数组如下所示:

public function page(){
  $content = readfile('modules/chess/templates/index.html.twig');
  $element = array (
    '#type' => 'markup',
    '#markup' => $this->t($content),
    '#attached' => array(
    'library' => 'chess/chess'
    ),
  );

  return $element;
}

所以它附加了国际象棋库。唯一显示的是带有损坏图像的 html,没有 css,并且页面底部有一条错误消息:

网站遇到意外错误。请稍后重试。

InvalidArgumentException:$string ("7864") 必须是字符串。在 Drupal\Core\StringTranslation\TranslatableMarkup->__construct() (行 core/lib/Drupal/Core/StringTranslation/TranslatableMarkup.php 的 133)。

据我所知,没有一个翻译模块被启用。有人知道我错过了什么吗?

更新: 我将控制器的

page()
功能更改为读取

public function page(){
  $content = readfile('modules/chess/templates/page.html.twig');
  $element = array (
    '#type' => 'markup',
    '#template' => $content,
    '#attached' => array(
      'library' => 'chess/chess'
    ),
  );

  return $element;
}

CSS 出现了,但图像还没有出现。源代码还仍然显示资产功能,而不是填充的脚本标签。

更新2: 我通过composer安装了symfony/asset,我的twig文件现在看起来像这样:

<link href="{{ asset('css/chess.css') }}" rel="stylesheet">
<script type="text/javascript" src="{{ asset('js/jquery-1.12.min.js') }}"></script>
...
<div class="piece black queen" id="black-queen"><img src="{{ asset('images/queen-black.png') }}" /></div>

CSS 显示出来,但内容显示在 drupal 页面其余部分的上方。有没有办法将页面放在 drupal 布局中的正确位置? (此外,图像未显示)。

更新3: 我从 page.html.twig 中删除了所有

src="{{ asset(...) }}"
标签,并且 javascript 似乎可以工作,CSS 也是如此。剩下的唯一事情是如何让页面在 drupal 页面的框架内(而不是在其之上)工作,以及如何包含图像。

html css drupal drupal-8
1个回答
0
投票

我认为你应该将其更改为

{{ attach_library('chess/chess') }}

而不是 CSS 文件的绝对路径。

© www.soinside.com 2019 - 2024. All rights reserved.