Variable Variable in Smarty Templates - smarty

I have a dynamically generated Smarty variable in PHP. I want to access it with name ,
Say for example there is a smarty variable {$asdf} which was generated dynamically and i have an array that has 'asdf' i want to use this array and access {$asdf}.
{$asdf} prints a input element [rendered] ;
$array = array('asdf');
{foreach from=$array item=x}
{$x}
{/foreach}
//but {$x} is not giving renderend input instead it is giving $asdf
where am i going wrong?

It is generally atypical to do this type of work in a template file. You should separate your template and logic as much as possible -- there's no plausible scenario in which you could not simply prepare the needed variables for your template in php and pass them on to the template in a useable structure.
That said, it is possible. Within a template, all variables that were passed to the template are accessible in an array, Smarty::_tpl_vars. Within a template, one may interact with this array using the {php}{/php} tags, where it can be referenced via $this --
{php}
$unknownValue = $this->_tpl_vars[
$this->_tpl_vars['known_key']
];
// for example...
$this->_tpl_vars['magicalValue'] = $unknownValue;
{/php}
Magic: {$magicalValue}
I cannot reiterate enough, however, that it is generally bad practice to place such logic inside a template.

Related

Is it possible to manipulate the output of a laravel #yield in the blade template?

Wondering if it is possible to manipulate the output of a #yield in Laravel? In short I have a title in my child template that I would like to set some id's with to make them unique. I know I could just create another #section('id', 'asdf') but rather not have to worry users with that especially since the title has to be unique anyways...
Could not find anything that says this is possible?
Example (which fails) but what I am essentially trying to do:
id="{{Str::kebab(#yield('title'))}}-preview-tab"
#yield gets replaced with a PHP echo statement so that is not what you want. If you want the content of a section you can grab it from the View Factory:
$__env->getSection($name, $default)
Or even calling yieldContent:
$__env->yieldContent($section, $default)
So you could try:
{{ Str::kebab($__env->getSection('title', 'some default if you want')) }}
If you have any issues with that, try the yieldContent method.

Laravel Blade directive adding extra quotes

Im using Laravel 7 so I didnt think this was going to be an issue.
Just a note on my installation, it was an upgrade from 5.3.
My issue is with a custom Blade directive I created.
It is aded additional quotes around the input
I added a dd() to see why my Helper didnt work.
My ServiceProvider
Blade::directive('setting', function ($expression) {
dd($expression);
return SettingHelper::value($expression);
});
View file
#setting('theme_public')
Output of dd()
"'theme_public'"
Expected output
'theme_public'
I dont know why the extra quotes are being added.
You are right, I get the same behavior with a fresh laravel 7 installation.
I created some little tests, to see what's going on. I think the behavior is best explained like this. Imagine you are calling a view with one variable:
return view('welcome', ['var' => "Hallo"]);
You have a custom blade directive like this:
Blade::directive('dirtest', function ($expression) {
dd($expression);
});
If you use that in your template the output is this:
#dirtest($var)
// output of dd in the browser:
"$var"
So it seems like the blade directives are just meant to replace some shorthand directive with more verbose php code. The actual code get's executed later in the blade templating engine. That makes sense, since blade templates are also cached for faster execution. In the cached version that custom directive is already embedded and your custom function doesn't get fired anymore. I hope that explanation makes sense to you.
What that means for you
It really depends on your use case. If you have a custom directive, that only gets passed constant strings, you could probably get away with just writing:
#setting(theme_public)
But if there's just a slight chance, that you might pass in a variable from time to time, like
#setting($theme)
You really have to return code, that utilizes that variable and can be evaluated later.

Thymeleaf: Building variable names dynamically

I am trying to build the name of a var dynamically by concatenating the value of a variable and adding some string afterwards, as I add these variable in runtime. Something like the following should work but it does not.
th:text="${__#{myClass.getA().getB()}+'-result'__}"
Is this even possible to do? I dont know the name of the variable, I can only construct it like this unfortunately.
Yes, that is possible, Thymeleaf supports expression preprocessing:
Let's start with some examples:
The message(i18n) expressions should be referenced using the # character. So let's suppose you have the message.key in your translation file. To reference it in Thymeleaf you will have to use
th:text="#{message.key}"
In your scenario your key name is generated dynamically based on a variable so for preprocessing it in thymeleaf you need to use two underscores __
Let's suppose in your context you have a model variable called myModelVariable with a method messagePrefix(). Our example becomes:
th:text="#{__${myModelVariable.messagePrefix()}__}"
This means the myModelVariable.messagePrefix() will be processed first and the result will be used as the key name which will be then resolved to a nice user friendly message.
And if you also want to add a static part at the end of it will look like this:
th:text="#{__${myModelVariable.messagePrefix()}__}+'*'"
Even the key can contain a static part so this is also accepted:
th:text="#{__${myModelVariable.messagePrefix()}__.staticsuffix}+'*'"
More info you can find in the section 2.7 here:
https://www.thymeleaf.org/doc/articles/standarddialect5minutes.html

How popular article module is working?

/modules/mod_articles_popular/tmpl/default.php
Can somebody explain me, how this working?
I do not understand how these $item->link and $item->title get correct information?
Where is MySQL query? Is it global variables? If yes, where they are described?
Any advice is much appreciated.
So, like most modules /tmpl/default.php is included on the last line the module entry point file i.e. mod_articles_popular.php
In that file helper.php is included first followed by
$list = modArticlesPopularHelper::getList($params);
As you can see this calls the getList() method of the helper class which performs the task of retrieving the $list of articles.
It (modArticlesPopularHelper) in turn loads the ContentModel and sets the state of the $model based on the default app params and the modules settings.
The it asks the model for the actual items required with the line $items = $model->getItems().
After that it loops through the items returned by the model and creates a link value for each article prior to returning it to the module.
As a result $list is filled with each of the article items which are pulled out individually in the foreach loop in /tmpl/default.php file.

Magento: how do I access custom variables in PHP?

I am aware of 'Custom Variables' and how they can be used with {{ }} brackets in email templates as well as in static blocks.
However, I want to use them in template code i.e. view.phtml.
I want to be able to access 'variable plain value' to retrieve a conversion value, i.e. a number/string as number for a given 'variable code'.
Been doing this for some time to create various messages that are editable through the admin interface so I don't have to go code digging when the flavor of the moment changes.
To access the plain value of the custom variable with code custom_variable_code use this:
Mage::getModel('core/variable')->loadByCode('custom_variable_code')->getValue('plain');
NOTE: Single store doesn't show the store select dropdown for the variable scope. This answer is not technically correct, in order to future-proof yourself in case of having multiple stores --> Please see #Mark van der Sanden answer below and give him an upvote.
Unfortunately, all other answers are not 100% correct. Use it like this (note the setStoreId() to get the value for the correct store view):
$value = Mage::getModel('core/variable')
->setStoreId(Mage::app()->getStore()->getId())
->loadByCode('variable_code')
->getValue('text');
Or to get the html value:
$value = Mage::getModel('core/variable')
->setStoreId(Mage::app()->getStore()->getId())
->loadByCode('variable_code')
->getValue('html');
If no html value is defined, getValue() returns the text value if you request the html value.
Stackoverflow almost to the rescue again. Thought this would be it:
Setting a global variable in Magento, the GUI way?
But it wasn't, this was:
$angle = Mage::getModel('core/variable')->loadByCode('angle')->getData('store_plain_value');
The only way I see you can acheive this by having a method in the templates block, that will output the needed result.
For instance say in the template view.phtml you have the following code:
<div id="title_container">
<h2><?= $this->getTitle(); ?></h2>
</div>
The function can represent your variable code and any logic that has to do with what gets displayed in the title should be placed in the block.
Just for clarification sake the block is the variable $this
If you are unsure what is the actual class name of your block you can do something like:
Mage::log(get_class($this));
in the var/log/system.log you will print the class of the block of that template.
That is the best way.
HTH :)
// To get the TEXT value of the custom variable:
Mage::getModel('core/variable')->setStoreId(Mage::app()->getStore()->getId())->loadByCode('custom_variable_code')->getValue('text');
// To get the HTML value of the custom variable:
Mage::getModel('core/variable')->setStoreId(Mage::app()->getStore()->getId())->loadByCode('custom_variable_code')->getValue('html');
// The store id is set as Custom Variables can be edited for multiple stores
Note: A custom variable might have different values for different stores.
So to access store specific value for the custom variable with the code custom_variable_code
Use this:
$storeId = Mage::app()->getStore()->getId();
$custom_variable_text = Mage::getModel('core/variable')->setStoreId($storeId)
->loadByCode('custom_variable_code')
->getValue('text');
$custom_variable_plain_value = Mage::getModel('core/variable')->setStoreId($storeId)
->loadByCode('custom_variable_code')
->getValue('plain');
$custom_variable_html_value = Mage::getModel('core/variable')->setStoreId($storeId)
->loadByCode('custom_variable_code')
->getValue('html');

Resources