Symfony – Accessessing Unescaped Multi-dimensional Array Values in Templates
A majority of the time, symfony templates are iterating through arrays set by a certain action in their respective actions class and if you have ESC_SPECIALCHARS set to ‘ON’ in your view.yml file, all the string values will have special chars converted from string values to html entities. For example a space looks like ‘ ‘ via render, but if you view html source you will see ‘ ’.
Escaping output is always a good idea, especially if you are allowing users to post comments (etc.) to your website. Escaping html entites ensures that any html they enter will not be rendered as html, which may wreck havoc with your site.
As great as escaping output is, there are times when you need to access raw values (unescaped). Let me give you an example. Say you have an multi-dimensional array like; $blogs['blogName'] which stores ‘Mike’s Dev Blog’. As you can see, the special char here is the apostrophe in Mike’s. In the symfony template if you echo $blogs['blogName'] and view html source you will see Mike's Dev Blog. & is the html entity for an apostrophe.
Why would you ever want to access the unescaped version of Mike’s Dev Blog? Simple, say we want to build a link using Mike’s Dev Blog as a querystring parameter. For example: http://melikedev.com/article?id=Mike’s Dev Blog . What’s wrong with this picture? Spaces, making it an invalid url, so we need to do a urlencode (or rawurlencode) so then the link looks like: http://melikedev.com/article?id=Mike’s+Dev+Blog, which works fine. The problem lies in the fact that accessing the value Mike’s Dev Blog within a symfony template can be tricky, consider the following example (template file):
foreach ($blogs as $blog): echo $blog['blogName']; //Displays Mike's Dev Blog in source html echo $blog->unescape($blog->get('blogName')); //Displays Mike's Dev Blog in source html echo urlencode($blog->unescape($blog->get('blogName'))); //Displays Mike's+Dev+Blog in source html endforeach;
As you can see in the above example we were able to access $blogs['blogName'] which is a multi-dimensional array.
It took some time to figure out b/c I was so used to simply doing $sf_data->getRaw(‘someVariable’), but this only works if you set $this->someVariable = ‘someValue’ in the actions class.
Hope this helps.
- Symfony – Share Template Across Multiple Apps
- PHP – Symfony – Speed up CLI Commands – Do Not Load Web Plugins
- PHP – Symfony – Build Model – No yml schema found
- Symfony – Propel – Determine Propel Version
- Symfony – Doctrine – Call to a member function evictAll on a non-object
- Symfony – Standard API for Logging Using __callStatic
- Symfony – Symfony 2 Security Audit Results
- Symfony – Serve External Apis from External Hosts – jQuery – Yui
- Symfony – sfGuardPlugin – Use Email Instead of Username
- Symfony – PHP – Possibly Forking 1.x so Invested Companies don’t Lose Millions