I’m writing a plug-in.
I want to be able to do something like
{exp:plugin:function id='12'}
{if has_records}
<ul>
{items}
<li>{name}</li>
{/items}
</ul>
{/if}
{/exp:plugin:function}the idea being that I will get a list of {names} if and only if there are some names to list.
I know how to do the conditional part.
I know how to extract the template pair with preg_match.
What I don’t know is how to process this ‘sub-template’ short of brute force. Is there anyway I can use EE functions to extract this (/these) tags and use var_single/swap_var_single to process this sub tag?
I’ve seen that there are plugins that do this, (e.g. query), but I’m not at all sure how to code it.
Thanks
Iain
[Mod Edit: Moved to the Plugins: Technical Assistance forum]
Well, as I’ve worked out how to do this, I thought I’d post a snippet of code.
What this does is to take a database query (in this case raw from mysql rather than using the ee $DB object), and show the results if there are some. The template code might read and will output a heading and the details for related items if there are some, or nothing otherwise.
{exp:companies:related_articles keyid=3}
{if has_records}
<h3>Related articles</h3>
<ul>
{items}
<li><a href="http://{path=news/article_page}{ArticleID}">{Title}, {ArticleType}, {CreationDate}</a></li>
{/items}
</ul>
{/if}
{/exp:companies:related_articles}
The code looks like
function related_articles()
{
global $TMPL;
$keyid = $TMPL->fetch_param('keyid');
$sql = "select cfa.ArticleID, a.Title, a.CreationDate from articles where companyid = $keyid";
$query = HPCI_RunSql($sql);
return ProcessRelatedSql($query);
}
function ProcessRelatedSql($query)
{
global $TMPL;
global $FNS;
$hasRecords = (mysql_num_rows($query) > 0);
if ($hasRecords)
$cond=array('has_records'=> 'TRUE');
else
$cond=array('has_records'=> 'FALSE');
$tagdata = $FNS->prep_conditionals($TMPL->tagdata, $cond);
// now if there are no records, we're done - no need to process them, else
if ($hasRecords)
{
foreach ($TMPL->var_pair as $key=>$val)
{
if (!(strpos($key, 'items') === false))
{
$matches;
if (preg_match("/".LD."$key".RD."(.*?)".LD.SLASH.'items'.RD."/s", $TMPL->tagdata, $matches))
{
$returnval = '';
$innerTag = $matches[1];
$vars = $FNS->assign_variables($innerTag);
$single_vars = $vars['var_single'];
$returnval = '';
while ($row = mysql_fetch_array($query, MYSQL_ASSOC))
{
$output = $innerTag;
foreach ($single_vars as $val)
{
if (isset($row[$val]))
$output = $TMPL->swap_var_single($val, $row[$val], $output);
}
$returnval .= $output;
}
$tagdata = preg_replace("/".LD."$key".RD."(.*?)".LD.SLASH."$key".RD."/s", $returnval, $tagdata);
}
}
}
}
return $tagdata;
}in essence we run a query in the main method. ProcessRelatedSQL first sees if there are results. it sets the conditionals accordingly. If there are results it looks for an {items} pair and processes the template fragment inside it once for each record.
Iain
Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.