smarty plugin to get the first image from a text

719 views Asked by At

I have a smarty variable that outputs an array like this:

$article = Array(10)
                  id => "103"
                  categoryid => "6"
                  title => "¿Cuánto espacio necesito para mi siti..."
                  text => "<img class="img-responsive center img..."

I need to extract the first image url from the $article.text and display it on the template. Because I want to dynamically create the facebook og:image property tag:

<meta property="og:image" content="image.jpg" />

I know that on php this code works:

$texthtml = $article['text'];
preg_match('/<img.+src=[\'"](?P<src>.+)[\'"].*>/i', $texthtml, $image);
return $image['src'];

But I don't want to use the {php} tags from smarty since they are deprecated.

So I just build a smarty plugin with the following code:

* Smarty plugin
* -------------------------------------------------------------
* File:     function.articleimage.php
* Type:     function
* Name:     articleimage
* Purpose:  get the first image from an array
* -------------------------------------------------------------
*/
function smarty_function_articleimage($params)
{
$texthtml = $article['text'];
preg_match('/<img.+src=[\'"](?P<src>.+)[\'"].*>/i', $texthtml, $image);
return $image['src'];
}

And I insert it into the template like this:

<meta property="og:image" content="{articleimage}" />

But it doesn't work :(

Any clues?

1

There are 1 answers

1
Don't Panic On BEST ANSWER

It looks like you need to pass your $article into the function.

In the Smarty Template Function documentation, it says that:

All attributes passed to template functions from the template are contained in the $params as an associative array.

Based on this documentation, it looks like the syntax for passing the variable would be like this:

{articleimage article=$article}

Then in the function, you should be able to get it from $params like this:

function smarty_function_articleimage($params)
{
    $text = $params['article']['text'];
    preg_match('/<img.+src=[\'"](?P<src>.+)[\'"].*>/i', $text, $image);
    return $image['src'];
}