You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过编程编辑区块主体?区块版权年份自动更新方案咨询

自动更新版权年份的解决方案(无需PHP Filter模块)

嘿,这个需求太常见了!既然不能用PHP Filter模块,创建一个轻量的自定义模块并调用特定hook确实是最可靠、最优雅的方案——而且完全不需要复杂代码,几步就能搞定。

下面给你两种实用的实现方式,选适合你的场景就行:

方式一:通过模板预处理hook传递变量

这种方法适合直接在主题模板里使用,步骤超简单:

  1. 创建一个极简的自定义模块(比如叫custom_copyright),只需要两个文件:

    • custom_copyright.info.yml(模块声明文件):
      name: Custom Copyright Year
      type: module
      description: Automatically updates copyright year without PHP Filter.
      core_version_requirement: ^9 || ^10
      package: Custom
      
    • custom_copyright.module(核心逻辑文件):
      /**
       * Implements hook_preprocess_page().
       */
      function custom_copyright_preprocess_page(&$variables) {
        // 获取当前4位年份
        $current_year = date('Y');
        // 将年份变量传递给page模板
        $variables['current_copyright_year'] = $current_year;
      }
      
  2. 启用这个模块后,修改你的主题模板(比如page.html.twig),把原来硬编码的年份替换成模板变量:

    © {{ current_copyright_year }} Some Company
    

这样每次页面渲染时,都会自动替换成当前年份,完美避开PHP Filter的安全风险。

方式二:创建自定义Token(更灵活)

如果需要在更多场景(比如Views、文本编辑器、区块内容)里使用自动年份,自定义Token是更好的选择,同样通过hook实现:

在刚才的custom_copyright.module里添加以下代码:

/**
 * Implements hook_token_info().
 */
function custom_copyright_token_info() {
  $info['tokens']['site']['current-year'] = [
    'name' => t('Current copyright year'),
    'description' => t('The current four-digit year for copyright notices.'),
  ];
  return $info;
}

/**
 * Implements hook_tokens().
 */
function custom_copyright_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'site' && !empty($tokens['current-year'])) {
    $current_year = date('Y');
    $replacements[$tokens['current-year']] = $current_year;

    // 配置缓存策略:确保年底自动刷新缓存,避免年份不更新
    $end_of_year = strtotime('December 31, 23:59:59');
    $bubbleable_metadata->setCacheMaxAge($end_of_year - \Drupal::time()->getRequestTime());
    $bubbleable_metadata->addCacheContexts(['timezone']);
  }

  return $replacements;
}

启用模块后,你就可以在任何支持Token的地方使用[site:current-year]这个标记了,比如区块内容里直接写:

© [site:current-year] Some Company

总结

回到你的问题:是的,你需要创建一个轻量的自定义模块,并调用hook_preprocess_HOOK或者Token相关的hook——这是替代PHP Filter模块最安全、可维护的方案,而且代码量极小,完全没有学习门槛。

内容的提问来源于stack exchange,提问作者ZST

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:05:25