简体   繁体   English

如何将 JSON 添加到一页的部分

[英]How to Add JSON to <head> Section of One Page

I want to add multiple Schema.org Event JSON objects to the head section of my front page.我想将多个 Schema.org 事件 JSON 对象添加到我的首页的标题部分。 The start and end dates need to be modified programmatically as time moves forward.随着时间的推移,需要以编程方式修改开始日期和结束日期。 The Schema.org module does not meet my needs. Schema.org 模块不符合我的需求。

Playing around in html.html.twig, it looks like the output of the Metatag and Schema.org modules are in head-placeholder token="{{ placeholder_token }}".在 html.html.twig 中玩耍,看起来 Metatag 和 Schema.org 模块的 output 在 head-placeholder token="{{ placeholder_token }}" 中。 I think I need to append my JSON to that placeholder in template_preprocess_html.我需要 append 我的 JSON 到 template_preprocess_html 中的那个占位符。

I have only done a small amount of _preprocess modifications, so if that is correct, any hints on how to append to that placeholder?我只做了少量的 _preprocess 修改,所以如果那是正确的,关于如何 append 到该占位符的任何提示? If is it not correct, can someone point me in the right direction?如果不正确,有人可以指出我正确的方向吗?

I did some exploration into how the Metatag module inserted its json and came up with this.我对 Metatag 模块如何插入其 json 进行了一些探索,并得出了这个结论。 I believe it will work.我相信它会奏效。

function hhc_page_attachments_alter(array &$attachments) {

   $path = \Drupal::request()->getRequestUri();

   //If it is not the home page, exit
   if ($path != '/')
     return;

  $attachments['#attached']['html_head'][] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'script',
      '#value' => "JDD PUT JSON CODE HERE",
      '#attributes' => ['type' => 'application/ld+json'],
    ],
    'schema_metatag',
  ];
}

Here is the complete solution I came up with.这是我想出的完整解决方案。 I realize this would probably be better done with a module making full use of the Drupal framework, but I do not know how to do that, Small site, small company.我意识到使用一个充分利用 Drupal 框架的模块可能会更好,但我不知道该怎么做,小网站,小公司。 and just me maintaining it, This works, is live.只有我维护它,这有效,是活的。 and validates at validator.schema,org.并在 validator.schema,org 进行验证。 and passed the test for rich results at search.google.com/test/rich-results.并在 search.google.com/test/rich-results 通过了富媒体搜索结果测试。

Perhaps this will help another beginner like myself.|也许这会帮助像我这样的另一个初学者。|

Problem Statement: Company has 2 events every month that start on the 1st and 15th of each month.问题陈述:公司每个月有 2 场活动,分别在每月的 1 号和 15 号开始。 Want Schema.org Event JSON for the next 4 upcoming events, output on the home page.想要 Schema.org 活动 JSON 了解接下来的 4 个即将举行的活动,主页上的 output。 The first event must start at least two weeks after "Today".第一个事件必须在“今天”之后至少两周开始。

/*
*  Gets the next start date of a retreat to be used in the Schema.org Event Type
*  Retreats always begin on 1st of 15th of the month.
*  Retreats to display will alway begin at least two weeks in advance, so always the next month.
*  To get the first upcoming retreat (first call of function), if current day is < 15,
*  get 1st of next month.  If 15 or >, get 15th of next month.
*  For the second upcoming retreat,
*/
function nextRetreat(DateTime $now, bool $firstCall) {

  $nextRetreat = new DateTime();

  if ($firstCall) {
    $now->modify('+1 month');
    $day = ($now->format('d') < 15)? 1 : 15;
    $month = $now->format('m');
    $year = $now->format('Y');
    $nextRetreat->setDate($year, $month, $day);
  }
  else {
    //If second call or more, the day of $now should be 1 or 15.  If one, we want the 15th of same month
    //If 15, we want first day of next month.
    if ($now->format('d') < 15) {
      $nextRetreat = $now->modify('+14 days');
    }
    else {
      $nextRetreat = $now->modify('first day of next month');
    }
  }

  return  $nextRetreat;

}


/*
*  Builds the Schema.org Event type with a subset of hard coded values.
*  This is hard coded for a 12 day retreat, and the endDate of the event
*  is 11 days after the start.
*
*  $start:  The start date of the event
*/
function buildEventJSON(DateTime $start) {

  $end = (clone $start)->modify('+11 days');

  $event = [
    "@context" => "https://schema.org",
    "@type" => "Event",
    "name" => "12 Day  Retreat",
    "image" =>"https://example.com/images/some-image.jpg",
    "description" => "Worlds best retreat of type Retreat.  You can't get a better retreat than the ones we are Retreating!",
    "startDate" => $start->format('Y-m-d')."T10:00",
    "endDate" => $end->format('Y-m-d')."T10:00",
    "eventStatus" => "https://schema.org/EventScheduled",
    "eventAttendanceMode" => "https://schema.org/OfflineEventAttendanceMode",
    "location" => [
      "@type" => "Place",
      "name" => "Great Retreat Center",
      "address" => [
          "@type" => "PostalAddress",
          "streetAddress" => "Main Street #226",
          "addressLocality" => "Lima",
          "postalCode" => "00000",
          "addressCountry" => "PE"
        ]
      ],
      "offers" => [
        [
          "@type" => "Offer",
          "name" => "9 Day Retreat",
          "price" => "180",
          "priceCurrency" => "USD",
          "validFrom" => "2022-01-01",
          "url" => "https://example.com/9-day-retreats",
          "availability" => "https://schema.org/InStock"
        ],
        [
          "@type" => "Offer",
          "name" => "12 Day Retreat",
          "price" => "220",
          "priceCurrency" => "USD",
          "validFrom" => "2022-02-01",
          "url" => "https://example.com/12-day-retreats",
          "availability" => "https://schema.org/InStock"
        ]
      ]
    ];

  return  json_encode($event, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE);

}



function hhc_page_attachments_alter(array &$attachments) {

   $path = \Drupal::request()->getRequestUri();

   //If it is not the home page, exit
   if ($path != '/')
     return;

  $nextRetreatStart = nextRetreat(new DateTime(), true);

  $attachments['#attached']['html_head'][] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'script',
      '#value' => buildEventJSON($nextRetreatStart),
      '#attributes' => ['type' => 'application/ld+json'],
    ],
    'my_event_1',
  ];

  // Change the start and end date and second event.
  $nextRetreatStart = nextRetreat($nextRetreatStart, false);
  $attachments['#attached']['html_head'][] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'script',
      '#value' => buildEventJSON($nextRetreatStart),
      '#attributes' => ['type' => 'application/ld+json'],
    ],
    'my_event_2',
  ];

  // Change the start and end date and third event.
  $nextRetreatStart = nextRetreat($nextRetreatStart, false);
  $attachments['#attached']['html_head'][] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'script',
      '#value' => buildEventJSON($nextRetreatStart),
      '#attributes' => ['type' => 'application/ld+json'],
    ],
    'my_event_3',
  ];

  // Change the start and end date and fourth event.
  $nextRetreatStart = nextRetreat($nextRetreatStart, false);
  $attachments['#attached']['html_head'][] = [
    [
      '#type' => 'html_tag',
      '#tag' => 'script',
      '#value' => buildEventJSON($nextRetreatStart),
      '#attributes' => ['type' => 'application/ld+json'],
    ],
    'my_event_4',
  ];

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM