【问题标题】:Drupal - Add a class to an existing button based on URLDrupal - 根据 URL 将类添加到现有按钮
【发布时间】:2015-09-10 21:42:11
【问题描述】:

我网站的每个页面上都有一个“立即预订”按钮。我想知道选择了哪个按钮,并且真的不想向站点添加 25+ 个块来手动添加类。如果我可以使按钮独一无二(根据页面 URL 添加一个额外的类),我可以使用 Google Analytics。但我不是编码员,虽然我熟悉 PHP 和 jQuery。

【问题讨论】:

  • 欢迎来到 StackOverflow 迈克尔!请查看stackoverflow.com/help/how-to-ask 以获取有关制作好问题的提示。在您的情况下,请包含您尝试过的代码。

标签: php jquery drupal-7


【解决方案1】:

Hye Michael,在阅读了您的问题后,我在本地测试 drupal 站点上测试了您的场景。实现它真的很容易。这是您需要放入您创建的块中的一段 PHP 代码。

<?php
$url = current_path();
$class_from_url = explode("/", $url);
echo "<a href=[link_to_whatever] class='". $class_from_url[0] ."'>[Link Title]</a>";
?>

确保您的“PHP 过滤器”模块已启用,这将允许您从块正文下的“文本格式”中选择 PHP 代码。

【讨论】:

  • 将 PHP 代码放在内容实体(节点、块等)中是一种不好的做法,并且出于各种原因不鼓励这样做。有关详细信息,请参阅drupal.stackexchange.com/questions/2509/…
  • 我知道这是一种不好的做法,但不受限制:)。另一方面,如果我们查看需求,这也是一种不好的做法。如果页面 url 中有特殊字符怎么办?他们也会去那个主播课。
【解决方案2】:

对于 Drupal 7,实现目标的最佳方法是将 theme_button() 函数复制到主题的 template.php 文件并添加一些自定义代码来检查 URL 并添加类。

YOURTHEME_button($vars) {
  $element = $variables ['element'];
  $element ['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element ['#attributes']['class'][] = 'form-' . $element ['#button_type'];
  if (!empty($element ['#attributes']['disabled'])) {
    $element ['#attributes']['class'][] = 'form-button-disabled';
  }

  // Check URL to determine what button class to add
  $button_class = null;
  $current_path = base_path() . request_path();
  switch ($current_path) {
    '/form1':
      $button_class = 'button-for-form1';
      break;
    '/form2':
      $button_class = 'button-for-form2';
      break;
  }
  if ($button_class !== null) {
    $element ['#attributes']['class'][] = $button_class;
  }

  return '<input' . drupal_attributes($element ['#attributes']) . ' />';
}

请注意,此方法只会为您明确指定的 URL 添加类,它会忽略可能包含在 URL 中的任何用户提供的参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 2015-08-03
    相关资源
    最近更新 更多