1. Сниппет
1.1 Первый сниппет с именем - GoogleAmp
- данный сниппет производит захват значения переменной page в URL и обрабатывает его: получает все необходимые данные страницы, которую необходимо отобразить. Оригинальный сниппет был доработан, т.е. доставле блок ELSE который отображает страницу ошибки 404, если указанной страницы не существует, т.е. в блоке ELSE в строке: $resource = $modx->getObject('modResource', 3); - замените цифру 3 на номер вашего ресурса для ошибки 404
Код: Выделить всё
<?php
$site_url = MODX_SITE_URL;
$base_url = MODX_BASE_PATH;
$get = modX::sanitize($_GET, $modx->sanitizePatterns);
$alias = urldecode($get['page']);
$resource = $modx->getObject('modResource', [
'alias'=>$alias,
'class_key'=>'modDocument'
]);
$prefix = 'amp.';
if ($resource) {
$placeholders = [
'pageid' => $resource->get('id'),
'pagetitle' => $resource->get('pagetitle'),
'content' => $resource->get('content'),
'canonical' => $modx->makeUrl($resource->get('id'), '', '', 'full'),
'published' => $resource->get('publishedon'),
'edited' => $resource->get('editedon'),
'robots' => $resource->getTVValue('meta-robots'),
];
$tvName = 'image';
$tvValue = $resource->getTVValue($tvName);
if (!empty($tvValue)) {
$image_url = $site_url.$tvValue;
$image_base = $base_url.$tvValue;
list($width, $height) = getimagesize($image_base);
$placeholders[$tvName] = $tvValue;
$placeholders[$tvName.'_width'] = $width;
$placeholders[$tvName.'_height'] = $height;
}
$modx->setPlaceholders($placeholders, $prefix);
}
else {
$resource = $modx->getObject('modResource', 3);
$placeholders = [
'pageid' => $resource->get('id'),
'pagetitle' => $resource->get('pagetitle'),
'content' => $resource->get('content'),
'canonical' => $modx->makeUrl($resource->get('id'), '', '', 'full'),
'published' => $resource->get('publishedon'),
'edited' => $resource->get('editedon'),
'robots' => $resource->getTVValue('meta-robots'),
];
$tvName = 'image';
$tvValue = $resource->getTVValue($tvName);
if (!empty($tvValue)) {
$image_url = $site_url.$tvValue;
$image_base = $base_url.$tvValue;
list($width, $height) = getimagesize($image_base);
$placeholders[$tvName] = $tvValue;
$placeholders[$tvName.'_width'] = $width;
$placeholders[$tvName.'_height'] = $height;
}
$modx->setPlaceholders($placeholders, $prefix);
}
- данный сниппет производит замену отдельных кусков кода текстовой части страницы, поскольку в стандарте AMP используются свои HTML теги, так AMP не понимает IMG, ему нужен AMP-IMG и т.д. Тут все просто, читаем стандарт AMP и построчно пишем варианты замен
Код: Выделить всё
<?php
$input = str_replace('" />', '" ></amp-img>', $input);
$input = str_replace('<img', '<amp-img', $input);
$input = str_replace('iframe', 'amp-youtube', $input);
$input = str_replace('src="http://www.youtube.com/embed/', 'data-videoid = "', $input);
$input = str_replace('allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen', ' ', $input);
return $input;
Новый шаблон можно назвать как угодно, я назвал AMP. Он нужен для ресурса, в котором выводится содержимое AMP-версии.
Код: Выделить всё
[[!GoogleAmp]]<!doctype html>
<html amp lang="en">
[[$AMPHead]]
<body>
<div id="wrapper">
[[$top-menu]]
<h1>[[+amp.pagetitle]]</h1>
<div class="seoLink">
<b> ✔</b> View the full version of the article <b><a href="[[+amp.canonical]]" title="[[+amp.pagetitle:htmlentities]]">[[+amp.pagetitle:htmlentities]]</a></b>
on sait: <b><a href="[[!++site_url]]" title="[[++site_name]]">[[++site_name]]</a></b>
</div>
<article>
[[+amp.content:ampCodeEntities]]
</article>
<div class="clearboth seoLink">
<b> ✔ <a href="[[+amp.canonical]]" title="[[+amp.pagetitle:htmlentities]]">[[+amp.pagetitle:htmlentities]]</a></b>.
Author: <b><a href="[[!++site_url]]" title="[[++site_name]]">[[++site_name]]</a></b>
</div>
[[$footerLink]]
[[$metrikaAmp]]
[[$footer]]
</div>
</body>
</html>
В отличие от стандартного шаблона, представленного в сети Интернет, здесь представлены дополнительные блоки:
2.1 Выводит предложение перейти к полной версии страницы на нашем сайте. Поскольку AMP запрещают всякую внешнюю рекламу, то нам желательно затащить людей на основной сайт, а вот для этого и представлен этот код.
Код: Выделить всё
<div class="seoLink">
<b> ✔</b> View the full version of the article <b><a href="[[+amp.canonical]]" title="[[+amp.pagetitle:htmlentities]]">[[+amp.pagetitle:htmlentities]]</a></b>
on sait: <b><a href="[[!++site_url]]" title="[[++site_name]]">[[++site_name]]</a></b>
</div>
Код: Выделить всё
<div class="clearboth seoLink">
<b> ✔ <a href="[[+amp.canonical]]" title="[[+amp.pagetitle:htmlentities]]">[[+amp.pagetitle:htmlentities]]</a></b>.
Author: <b><a href="[[!++site_url]]" title="[[++site_name]]">[[++site_name]]</a></b>
</div>
[[$footerLink]] - выводит блок ссылок на страницы сайта, вот такая перелинковка
[[$metrikaAmp]] - установка счетчика метрики. AMP страницы запрещают внешний JS код, но у LiveInternet счетчика есть специальная версия для AMP страниц - берем ее.
[[$footer]] - просто подвал сайта. В оригинальной версии он был простой, поэтому решил его оставить и в AMP версии
3. Чанк
Чанк я назвал AMPHead, он содержит мета-теги. Этот код можно разместить и в шаблоне, но я не стал умничать и сделал, как у автора.
Код: Выделить всё
<head>
<meta charset="utf-8" />
<title>[[+amp.pagetitle:htmlentities]]</title>
<meta itemprop="name" content="[[+amp.pagetitle:htmlentities]]" />
<meta itemprop="description" content="[[+amp.pagetitle:htmlentities]]. Decisions for secure and stable logging in. [[+amp.description:htmlentities]]" />
<meta itemprop="image" content="[[!++site_url]][[+amp.image:default=`images/computer.jpg`]]" />
<meta name="robots" content="[[+amp.robots:default=`all`]]"/>
<meta name="mobile-web-app-capable" content="yes" />
<meta name="application-name" content="[[++site_name]]" />
<link rel="canonical" href="[[+amp.canonical]]" />
<link rel="icon" type="image/vnd.microsoft.icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1" />
<script async custom-element="amp-analytics" src="http://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>
<script async custom-element="amp-youtube" src="http://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script>
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "NewsArticle",
"headline": "[[+amp.pagetitle]]",
"datePublished": "[[+amp.published]]",
"dateModified": "[[+amp.edited]]",
"author": "[[++site_name]]",
"mainEntityOfPage": {
"@type": "WebPage",
"@id": "[[++site_url]]"
},
"publisher": {
"@type": "Organization",
"name": "[[++site_name]]",
"logo": {
"@type": "ImageObject",
"width": "750",
"height": "500",
"url":"[[!++site_url]]images/computer.jpg"
}
},
"image": {
"@type": "ImageObject",
"width": "[[+amp.image_width:default=`750`]]",
"height": "[[+amp.image_height:default=`500`]]",
"url":"[[!++site_url]][[+amp.image:default=`images/computer.jpg`]]"
}
}
</script>
<script async src="http://cdn.ampproject.org/v0.js"></script>
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
<style amp-custom>
body{
background-color: #fff;
line-height: 25px;
font: 15px arial,sans-serif;
line-height: 25px;
background: #eee;
}
.centered{text-align:center}
#wrapper {
max-width: 1100px;
margin: 0 auto;
background: white;
}
#header{
height: 45px;
border-bottom: 1px solid #d8d8d8;
background-color: #3366cc;
}
.main_header{
height: 45px;
background-color: #3366cc;
}
.logo_text {
float: left;
height: 15px;
font-size: 23px;
font-weight: bold;
color: #ffffff;
padding: 15px 20px;
}
.logo_text a {
text-decoration: none;
color: inherit;
}
#top_menu {
max-width: 559px;
text-align: right;
}
#top_menu, #sidebar_text {
float: left;
padding: 15px 0;
text-align: center;
}
div.main_menu_top ul {
margin: 0;
padding-left: 0;
}
div.main_menu_top ul li {
display: inline;
padding: 3px 15px;
font-size: 15px;
font-weight: bold;
border-left: 1px solid rgba(44, 94, 153, 1);
}
div.main_menu_top ul li a {
text-decoration: none;
text-shadow: #184774 1px -1px;
color: #ffffff;
}
div.main_menu_top ul li a:hover {
color: white;
color: #0645ad;
text-shadow: none;
}
#sidebar_text {
max-width: 289px;
font-weight: bold;
font-size: 15px;
}
#sidebar_text p {
margin: 0;
width: auto;
text-align: center;
color: #fff;
}
article {
padding: 10px;
color: #111;
}
h1 {
background-color: #fff;
color: #222;
font-weight: normal;
font-size: 1.5rem;
margin: 0;
padding: 1rem 0.25rem 0.25rem;
}
.img-200{
width:200px;
height:200px;
}
.img-r{float: right;margin-left: 20px;}
.img-l{float: left;margin-right: 20px;}
.img-b{border: 2px groove #BEBEBE;}
.header {
background-color: #3366cc;
padding: 0.5rem;
}
.p {
font-size: 15px;
}
.h4,h4{margin: 5px 0 0 7px;font-size: 15px;color: #063177;}
.seoLink{border-top: 1px solid #184774;border-bottom: 1px double #184774;margin:0 0 13px 0;padding:7px 13px;}
.dopFooterMenu{font-size: 12px;border-top: 1px solid rgba(58, 124, 202, 1);clear: both;background-color: #F0FFFF;}
.footerMenuBlock{float:left;max-width:270px;font-size:13px;}
.footerMenuBlock p{margin:7px 0 0 7px}.footerMenuBlock ul{margin:7px 7px 7px 0;}
.clearboth{clear: both;}
#footer {
background-color: #3366cc;
color: #fff;
text-shadow: #184774 0 -1px;
font-size: 12px;
font-weight: normal;
margin: 0;
padding: 1px;
text-align: center;
clear: both;
}
img, amp-img {
border: none;
max-width: 100%;
height: auto;
display: block;
margin: 5PX auto;
}
</style>
3.1 Код рабочий полностью, вот только долго я мучился с активным содержимым типа ВИДЕО с YOUTUBE - не хотело работать, оказалось нужно HEAD прописать еще несколько строк - в этом варианте они уже есть.
3.2 В коде представлен мой CSS - можете поменять на свой. Т.к. в AMP особо не разгуляешься, то минимальное количество стилей может жить и тут, а не в отдельном файле.
4. Ресурс
Далее нужно создать ресурс. Можно назвать его как угодно, главное — указать у него ранее созданный шаблон AMP.
Это входная точка у всех AMP-страниц. Этой странице будет передаваться GET-параметр, содержащий псевдоним (alias) страницы, например:
Код: Выделить всё
http://berdck.org/amp?page=dh.pochta-s-vashim-imenem
В HEAD шаблона оригинальных версий страниц нужно добавить мета-тег, указывающий на адрес AMP-версию текущей страницы
Код: Выделить всё
<link rel="amphtml" href="[[~id? &scheme=`[[++server_protocol]]` &page=`[[*alias]]`]]" />
В итоге на каждой странице будет вот такой код в HEAD
Код: Выделить всё
<link rel="amphtml" href="http://berdck.org/amp?page=dh.pochta-s-vashim-imenem" />