Converting img image to amp-img Bitrix

Order a service
2 min.
In this article, I will not go into detail about what AMP is, since the information here is intended for those who are already familiar with the technology and have already started implementing it. We will talk about images for the AMP template of the Bitrix website.

We already know that special accelerated mobile pages are built on the so-called AMP-HTML markup, which uses its own tags and does not allow the use of some tags of the usual HTML 5 markup. The list of these prohibited tags also includes the img tag. Now it is called amp-img.

It would seem that what is the problem, that we should get the address of the image in php and correctly form the amp-html markup on Bitrix. Of course, there can be no problems here. We take DETAIL_PICTURE, PREVIEW_PICTURE or images from some PROPERTY_, and correctly display it, specifying the layout, height, width, title and alt attributes of our AMP image on Bitrix. Yes, and do not forget about the main attribute src or srcset, if we use several images for different screen sizes. But when creating a template, I encountered one problem. Many images are already in the html markup of the detailed text (DETAIL_TEXT) of our articles and product descriptions. What to do here? I dug around on American sites and found a good solution.

Replacing img in amp-img on Bitrix

And the solution turned out to be very simple. Although maybe I wouldn't have written it myself, since I'm not good with regular expressions without a cheat sheet. The whole point is to replace the standard tags with new ones. Well, and since img doesn't have a closing tag, then add a closing tag at the end for our modernized image.

I will show you using the news.detail component as an example. In the component template, create the result_modifier.php file if it does not exist, and fill it with the following code.

$arResult["DETAIL_TEXT"] = _img_to_amp($arResult["DETAIL_TEXT"]);

function _img_to_amp ($html) {
preg_match_all("##", $html, $matches);
foreach ($matches[1] as $key => $m) {
preg_match_all('/(alt|title|src|width|height)=("[^"]*")/i', $m, $matches2);
$amp_tag = ' foreach ($matches2[1] as $key2 => $val) {
$amp_tag .= $val .'='. $matches2[2][$key2] .' ';
}
$amp_tag .= 'layout="responsive"';
$amp_tag .= '>';
$amp_tag .= '
';
$html = str_replace($matches[0][$key], $amp_tag, $html);
}
return $html;
}
?>

That's it, done! Now when the detailed page of the news item is displayed, all the images in the detailed text will be replaced with AMP-IMG.

But in the text of the announcement we wanted to remove these pictures altogether, if they were somewhere. Well, just in case. For this we used the following line of code:

$arResult["PREVIEW_TEXT"] = preg_replace('/]*)?>/i', '', $arResult["PREVIEW_TEXT"]);
?>

15 April 2020 (Boudybuilder) Виталий Фантич

Back to the list


Related Information: