【问题标题】:How to show content of a custom block using PHP code format in Drupal 8如何在 Drupal 8 中使用 PHP 代码格式显示自定义块的内容
【发布时间】:2016-04-29 17:01:10
【问题描述】:

我使用 PHP 代码格式在块中添加了一些自定义代码,以在特定页面上显示该块。我已经检查了在 Devel PHP 页面上一切正常,但页面上没有显示内容。下面的代码获取目标节点的字段值。

    $refer = $_SERVER[HTTP_REFERER];
    $parsed = parse_url($refer);
    $alias = array_pop($parsed);
    $dst = \Drupal::service('path.alias_manager')->getPathByAlias($alias , $langcode);
    $nid = array_pop(explode('/', $dst));
    $dest_node = node_load($nid);

    $body = $dest_node->get('body')->getValue();
    print $body; //have tried other printing methods also but invain

希望这可以澄清问题。 谢谢

【问题讨论】:

    标签: drupal drupal-8


    【解决方案1】:

    你确定它在 Devel 中有效吗?我刚刚尝试执行您的代码,这一行:

    $body = $dest_node->get('body')->getValue();
    

    返回数组。

    尝试改用这个:

    $body = $dest_node->body->value;
    

    【讨论】:

    • @Zubi 它仅适用于节点的页面(即“node/123”或别名)。所以你的意思是它有时可以在这些节点的页面上工作(在某些节点上有效,而在某些节点上无效)?如果页面是一种View,显然是不行的。
    • 我检查了日志,它给出了这一行的错误`$nid = array_pop(explode('/', $dst));` 严格警告:只有变量应该在 eval() 中通过引用传递
    • 是的,我将它用于节点页面。
    • 能否请您提供导致此错误的节点的别名。
    • 它是一个联系页面“/contact”
    【解决方案2】:

    首先,你的第一个代码块(获取当前节点)可以只用一行替换:

    $node = \Drupal::service('current_route_match')->getParameter('node');
    

    并且可以通过以下方式更改整个块:

    if ($node = \Drupal::service('current_route_match')->getParameter('node')) {
      print $node->body->value;
    }
    

    附:使用 PHP 文本过滤器绝对是个坏主意。您可以轻松编写自己的自定义模块,提供所需的块。最简单的块插件需要几行代码:

    /**
     * @file
     * Contains \Drupal\my_module\Plugin\Block\MyBlock.
     */
    
    namespace Drupal\my_module\Plugin\Block;
    
    use Drupal\Core\Block\BlockBase;
    
    /**
     * Provides my super block.
     *
     * @Block(
     *   id = "my_module_block",
     *   admin_label = @Translation("My Block"),
     *   category = @Translation("My Module"),
     * )
     */
    
    class MyBlock extends BlockBase{
    
      /**
       * Builds and returns the renderable array for this block plugin.
       *
       * @return array
       *   A renderable array representing the content of the block.
       *
       * @see \Drupal\block\BlockViewBuilder
       */
      public function build() {
        if ($node = \Drupal::service('current_route_match')->getParameter('node')) {
          return [ '#markup' => $node->body->value ];
        }
      }
    }
    

    此文件MyBlock.php 必须放在名为my_module 的自定义模块内的/src/Plugin/Block/ 目录中。

    【讨论】:

      猜你喜欢
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      相关资源
      最近更新 更多