Jump to content

How To Intercept <img> elements before page rendered


Gazley
 Share

Recommended Posts

Hi there,

I have images in fixed locations in certain templates but, images can also be inserted by the user in TinyMCE.

I would like to be able to wrap all images with extra markup before the page is rendered, whether they be specified in the template or whether they are inserted into a TextArea.

This sounds like API territory but would like to know the best approach, if anyone has ideas around this requirements.

Many thanks! :)

Link to comment
Share on other sites

Hi diogo

Thanks for the heads up - it's not so much as how to do it but how I intercept the markup before it's rendered. Javascript is a no go as the markup needs to be read by various bots so needs to be rendered in the markup server-side.

Cheers!

Link to comment
Share on other sites

In a autoload module you could hook the page render and replace all img tags.


public function init() {
 $this->addHookAfter('Page::render', $this, 'hookPageRender');
}

public function hookPageRender(HookEvent $event) {
 $out = $event->return;
 if(strpos($_SERVER['REQUEST_URI'],$this->config->urls->admin) === 0 ) return;
 $img_regex = '%(<img.*/>|</img>)%ixU';
 $event->return = preg_replace($img_regex, "<div class='img'>$1</div>", $out);
}

If you want to only replace certain images in the body you could use some markers or a html parser like php simple html dom http://simplehtmldom.sourceforge.net/

  • Like 3
Link to comment
Share on other sites

Hey Soma,

Thanks so much for your reply.

I've used simplehtmldom before and it's really, really good.

I guess I was trying to see what the PW way of doing this would be without the expense of firing up a third party tool and thanks to you, I now know! :)

Cheers!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...