Search code examples
phpmustachemustache.php

PHP Mustache - Run data through function while templating


I'm a beginner in Mustache and I am trying to implement it in my project. It worked without Mustache. I have no idea how to do the following (perhaps because I don't know what keywords to Google for?).

I'm sorry if the question title is unclear. I don't know how to phrase it in a clearer way. If someone can help me edit the title, that would be the best.

Basically, I have an array of background colors that I want to convert, into CSS internal style. But I also want to process the array before printing it out, to generate the text color of each background color in the array.

The color array:

$colors = array(
    array(
        "name" => "blue",
        "hex" => "#6CC5FA"
    ),
    array(
        "name" => "red",
        "hex" => "#840715"
    ),
    ...
)

I have a function that accepts an input color string and outputs the contrasting text color. And currently, I am using loops to echo out the <style>

I want to print out the output like this:

<style>
.bg-blue {
    background-color:#6CC5FA;
    color: #333333  /*This is the contrast color*/
}
.bg-red {
    background-color:#840715;
    color: #ffffff
}
....
</style>

The current method (obviously without Mustache) is something like this:

echo "<style>";
for ($i=0;i<sizeof($colors);i++) {
    echo ".bg-".$colors[$i]["name"]....contrastColor($colors[$i]["hex"])....;
    //You get the idea
}
echo "</style>";

I know that I can use a loop to push the generated text colors into the $colors then template with Mustache, but is there a way to slip the function into the template and tell Mustache to run the color codes through it?

Is there something like this?

$color_template = '
<style>
{{#color}}
.bg-{{name}} {
    background-color:{{hex}};
    color: {{contrastColor(hex)}}
}
{{/color}}
</style>
';

Solution

  • Yep! You can use the FILTERS pragma to do just that:

    {{% FILTERS }}
    <style>
      {{# color }}
        .bg-{{ name }} {
          background-color: {{ hex }};
          color: {{ hex | contrastColor }};
        }
      {{/ color }}
    </style>