1

次のような配列を出力する smarty 変数があります。

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

$article.text から最初の画像 URL を抽出し、テンプレートに表示する必要があります。Facebookのog:imageプロパティタグを動的に作成したいので:

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

私はphpでこのコードが機能することを知っています:

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

しかし、smarty の {php} タグは非推奨であるため、使用したくありません。

そこで、次のコードを使用して smarty プラグインを作成します。

* 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'];
}

そして、次のようにテンプレートに挿入します。

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

しかし、うまくいきません:(

手がかりはありますか?

4

1 に答える 1

1

$articleを関数に渡す必要があるようです。

Smarty Template Function documentationでは、次のように述べています。

テンプレートからテンプレート関数に渡されるすべての属性は、連想配列として $params に含まれています。

このドキュメントに基づくと、変数を渡すための構文は次のようになります。

{articleimage article=$article}

次に、関数では、次のように取得できるはずです$params

function smarty_function_articleimage($params)
{
    $text = $params['article']['text'];
    preg_match('/<img.+src=[\'"](?P<src>.+)[\'"].*>/i', $text, $image);
    return $image['src'];
}
于 2015-08-11T21:50:57.817 に答える