How to add canonical tag the pages that are derived from same link?

懵懂的女人 提交于 2019-12-05 11:41:51

According to an old ticket (based on an old thread in the old symfony forum) - which point to the final source, you can esaily create an helper that add a link tag to your page (for example /lib/helper/CanonicalHelper.php):

/**
* Add link tag to slot 'links'
*
* @param String $href [Absolute or internat URI]
* @param String $rel [value for 'rel' attribtue, e.g. 'canonical']
*
* @return void
*/
function add_link($href, $rel)
{
  $slot = get_slot('links');

  try {
    $href = url_for($href, true);
    $slot .= "\n<link rel=\"$rel\" href=\"$href\" />";
  } catch (InvalidArgumentException $e) {
    $slot .= "\n<!-- Could not add Link '$href': Only absolute or internal URIs allowed -->";
  }

  slot('links', $slot);
}

Then you can call it in your template:

<?php add_link(
  'http://newe4s.com/news/articles/view/033/job-news-and-information',
  'canonical'
); ?>

Finally, don't forget to add the slot in your layout.php:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Title</title>
    <link rel="shortcut icon" href="/favicon.ico" />
    <?php include_javascripts() ?>
    <?php include_stylesheets() ?>
    <?php include_slot('links'); ?>
  </head>

If you want to add it from the actions, it is defined in the blog post too.

edit:

If you create an helper called CanonicalHelper.php don't forget to include it when you want to use add_link function:

<?php use_helper('Canonical') ?>

Symfony 1.0.11

Important part is slot('links') & end_slot() so whatever print in between will be assigned to slot similar to ob_start & ob_end()

function add_link($href, $rel)
   {
      slot('links');
      echo "\n<link rel=\"$rel\" href=\"$href\" />\n";
      end_slot();
   }

Hi I am doing as below and please let me know If I am right or wrong.

In /lib/symfony/CanonicalHelper.php

<?php 
function add_link($href, $rel)
{
 $slot = get_slot('links');
 try {
  $href = url_for($href, true);
  $slot.= "\n<link rel=\"$rel\" href=\"$href\" />";
 }
 catch (InvalidArgumentException $e) {
 $slot.= "\n<!-- Could not add Link '$href': Only absolute or internal URIs allowed   -->";
}
 return $slot;
}
?>

In layout.php:

<?php include_slot('links'); ?>

In Success file:

<?php use_helper('Canonical');?>
<?php echo add_link('nonsense', 'canonical');?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!