I need to render a string from another string with macroses, using values from AR model. For example:
$template = 'Hello, {{username}}! Welcome to {{application.name}}. {{message}}'; // Syntax does not matter: %variable%, {{variable}} etc.
$macroses = [
'username',
'application.name',
'message',
];
$model = new TestModel;
$result = (new SomeComponent)->render($template, $macroses, $model);
/* All entries of macroses must be replaced with corresponding model attributes, its related record attributes or getter result:
{{username}} must be replaced with $model->username (attribute value)
{{application.name}} must be replaced with $model->application->name (related record attribute value)
{{message}} must be replaced with $model->getMessage() (result of getter method)
*/
The question is how to implement this with Yii2 built-in capabilities? Maybe I can somehow use Twig/Smarty renderers to replace macroses? How can I get an array of values from ActiveRecord, using such syntax (‘application.name’ for relations, ‘message’ for getters etc)?
I think you have it right. The Yii2 Gridview column configuration is very similar to what you have and the values are parsed almost similarly using the DataColumn.
Normally echo / return strings (render being a method for view files). Having said that, based on your design, you may want to use templates (Twig/Smarty) as well.
Just a thought… something as simple as strtr OR Yii::t could be used to parse strings and tags within strings in one statement.
For replacing params I can use also preg_replace_callback. My questions is about built-in template renderers (Twig/Smarty): can I use them for this? Replacing with preg_replace_callback or strtr is simple solution, of course, but with template renderers I can use not only param replacing, but also some logic (iterations, conditions and so on).