@christiana83, Did some playing with code. The following onPageContentProcessed
event handler seems to work.
Note: Used images are in pageās folder.
public function onPageContentProcessed($event) {
$page = $event['page'];
$media = $page->getMedia();
$content = $page->getRawContent();
// Get all <img> elements
$matches = [];
preg_match_all('#<img.*src="([^"]+)".*?/>#' , $content , $matches);
$contentChanged = false;
for($i = 0; $i < count($matches[0]); $i++) {
// Skip <img> elements that already contains width and/or height
if (preg_match('#(width|height)#', $matches[0][$i])) {
continue;
}
$src = $matches[1][$i];
$filename = substr($src, strrpos($src, '/') + 1);
$img = $media->get($filename);
$oldElement = substr($matches[0][$i], 0, -2);
$newElement = $oldElement . 'width="' . $img['width'] . '" height="' . $img['height'] . '"';
$content = str_replace($oldElement, $newElement, $content);
$contentChanged = true;
}
if ($contentChanged) {
$page->setRawContent($content);
}
}
Pageās Markdown:
![Image1](image1.jpg)
![Image2](image2.jpg)
Generated HTML:
<p>
<img alt="Image1" src="/user/pages/01.home/image1.jpg" width="1200" height="800"/>
<img alt="Image2" src="/user/pages/01.home/image2.jpg" width="639" height="481"/>
</p>
Alternatives:
1.
Update Markdown by one-time run of plugin.
You could also loop through all pages in onPagesInitialized
and update the Markdown. This should be a one-time action updating all pages once and for all.
// default.md
---
title: Home
body_classes: 'title-center title-h1h2'
---
![Image1](image1.jpg?classes=myclass)
![Image2](image2.jpg?resize=400,200)
// plugin onPagesInitialized event
public function onPagesInitialized($event) {
$pages = $event['pages'];
foreach($pages->all() as $page) {
$raw = $page->raw();
$media = $page->media();
$matches = [];
preg_match_all('#!\[[^\]]*\]\(([^?)]+)[^)]*\)#', $raw, $matches);
for($i = 0; $i < count($matches[0]); $i++) {
if (preg_match('/(height|width)/', $matches[0][$i])) {
continue;
}
$src = $matches[1][$i];
$img = $media[$src];
$oldMarkdown = $matches[0][$i];
$newMarkdown = str_replace('?', '?width=' . $img['width'] . '&height=' . $img['height'] . '&', $oldMarkdown);
$raw = str_replace($oldMarkdown, $newMarkdown, $raw);
$page->raw($raw);
$page->save();
}
}
}
// Updated default.md
---
title: Home
body_classes: 'title-center title-h1h2'
---
![Image1](image1.jpg?width=639&height=481&classes=myclass)
![Image2](image2.jpg?width=1200&height=800&resize=400,200)
2.
Admin onSave
You could of course do something similar when Admin saves a page.