1

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?

Valerie Castle
  • 113
  • 1
  • 11
  • I don't know smarty too well, but `$article` appears to be undefined in your function. – Don't Panic Aug 11 '15 at 21:12
  • I just updated my question $article is a variable that outputs an array. – Valerie Castle Aug 11 '15 at 21:15
  • I see `$article` in the first part of your question, but in the `smarty_function_articleimage` function, you set `$texthtml = $article['text']`, and at that point, `$article` has not yet been defined within the scope of that function, as far as I can tell. – Don't Panic Aug 11 '15 at 21:19

1 Answers1

1

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'];
}
Don't Panic
  • 41,125
  • 10
  • 61
  • 80