【问题标题】:Using str_replace to alter a field's display in a Drupal 7 view使用 str_replace 在 Drupal 7 视图中更改字段的显示
【发布时间】:2017-11-16 17:58:25
【问题描述】:

我正在使用 Google Analytics 模块检索过去一天在我的网站上最受欢迎的文章,以填充“趋势”块。

问题在于PageTitle 字段来自元数据并且包含管道和站点名称。我想从字符串的末尾去掉它,但我不知道如何在视图中使用rewrite results

我创建了一个views-view-field--pageTitle.tpl.php 文件并将其编辑为:

<?php 
$output = str_replace(" | My Site", "", $output);
print $output;
?>

这似乎不起作用...

【问题讨论】:

  • 已编辑以显示我刚刚尝试过的内容...

标签: php drupal drupal-7


【解决方案1】:

在 template.php 中使用预处理器肯定会起作用。还有其他选项可以更改页面,但这取决于您用于生成该标题的模块和设置,显然是在某处使用模式定义,所以不知道我的建议是使用这样的预处理器

 function THEME_NAME_preprocess_page(&$variables) {
   //you could use arg to identify your page page
  //https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/arg/7.x
    // if the page is the one you are looking then override the title
     drupal_set_title('mytitle');
 }

【讨论】:

  • 不是节点的标题。这是一个属于 Google Analytics 数据的字段,“页面跟踪:页面标题”我想我需要知道如何让一个字段以与数据库中的内容不同的方式显示,因为我想用任何内容替换字符串的结尾
【解决方案2】:

我认为你必须修改 template.php 中的元数据,所以你可以这样做:

THEMENAME_html_head_alter(&$head_elements) {
  // dump content of $head_elements and find your value to modify
}

文档:https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_html_head_alter/7.x

您还可以使用元数据模块来处理元数据: https://www.drupal.org/project/metatag

希望对你有帮助;)

【讨论】:

  • 我不想更改元数据,我希望元数据中包含站点名称。我只需要在我自己的网站上显示它时将其删除。
  • 这样您就可以在您的密钥上使用 unset() 函数
【解决方案3】:

如果您确定它始终将其返回为My Article Title | My Web Site,您可以在| 处拆分字符串。

$result = "My Article Title | My Web Site";   //the string that was returned
$splitResult = explode(" | ", $result);       //split the string at " | ", creating an array: ["My Article Title", "My Web Site"]
$articleTitle = $splitResult[0];              //get the first item in the array

【讨论】:

  • 是的,可以。你知道我需要在哪里放置代码来让视图显示新字符串吗?
  • 我不熟悉 drupal 的具体工作原理,但我认为您可以将它放在您想要在代码中存储/显示文章标题的任何位置。
猜你喜欢
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多