Search code examples
phpexpressionengine

ExpressionEngine: Pass parameter into variable tag pair and fetch in the function


I need to pass parameter into inner tag, ex.

{exp:myplugin:func}
  {last_year subject="xxx"}

  {/last_year}
{/exp:myplugin:func}

How can I fetch that parameter in the function?


Solution

  • Here's a function I've written to return the parameters for a variable pair inside a template tag pair:

    private function get_variable_parameters($tagData, $varName) {
        $parameters = array();
    
        if (strpos($tagData, LD."/".$varName.RD) !== FALSE) {
            //###   Closing variable tag exists   ###
            if (preg_match_all("/".LD.$varName."(.*?)".RD."(.*?)".LD."\/".$varName.RD."/s", $tagData, $matches)) {
                for ($num = 0; $num < count($matches[0]); $num++){
                    $allParams = explode(" ", trim($matches[1][$num]));
                    foreach($allParams as $value) {
                        $value = str_replace(array('"', "'"), '', $value);
                        $param = explode("=", $value);
                        if (!empty($param[1]))
                            $parameters[$param[0]] = $param[1];
                    }
                }
            }
        }
    
        return $parameters;
    }//###   End of get_variable_parameters function   ###
    

    So from your example code in your func method:

    $tagData = ee()->TMPL->tagdata;
    $varParameters = $this->get_variable_parameters($tagData, "last_year");
    echo $varParameters["subject"];
    

    Looking back over my code though, I don't think it handles multiple use of the same variable pair inside the same loop, so if required may need to change this line:

    $parameters[$param[0]] = $param[1];
    

    to:

    $parameters[$num][$param[0]] = $param[1];
    

    And then work out what instance of the variable pairs inside the same loop. Untested though, probably needs more work!