我正在使用 symfony 1.0.6。
在我的站点中,我有两个 URL。
http://newe4s.com/news/articles/view/033/job-news-and-information
和
http://newe4s.com/news/articles/view/033/job-news-and-information/graduate/Connections-help-graduates-get-jobs
现在,所有新文章都使用相同的布局,并且上面的两个链接都从数据库中获取相同的数据。 谷歌正在报告内容重复,因为它正在为同一内容获取多个 URL。 当我搜索解决方案时,我发现使用“规范”结构可以解决这个问题,这需要
<link rel="canonical" href="http://newe4s.com/news/articles/view/033/job-news-and-information />
添加到页面的头部
http://newe4s.com/news/articles/view/033/job-news-and-information/graduate/Connections-help-graduates-get-jobs
但这里的问题是,两者都使用相同的布局并基于文章 ID(上例中的 033)获取并显示数据。 我无法更改或硬编码规范 href。
有没有办法在 action.class 或模板文件中手动添加链接标签?
最佳答案
根据 an old ticket (基于 old thread in the old symfony forum ) - 哪一点 to the final source ,您可以轻松创建一个帮助程序,将链接标记添加到您的页面(例如 /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);
}
然后你可以在你的模板中调用它:
<?php add_link(
'http://newe4s.com/news/articles/view/033/job-news-and-information',
'canonical'
); ?>
最后,不要忘记在 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>
如果你想从 actions
添加它,它也在博客文章中定义。
编辑:
如果您创建了一个名为 CanonicalHelper.php
的助手,请不要忘记在您要使用 add_link
函数时包含它:
<?php use_helper('Canonical') ?>
关于hyperlink - 如何为来自同一链接的页面添加规范标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10947313/