I just wanted to know if there is this function in Symfony2 that would print human-readable information about a variable (the same as print_r() in PHP)?
Thanks
You can use the {{ dump(the_variable) }} function from Twig.
It is a helper, equivalent of var_dump in PHP, contained in a output buffer.
To enable such function, please check that in your config.yml file, this is configured:
twig:
...
debug:%kernel.debug%
Related
I'm trying to write a template in Twig. Inside it I would like it to perform some manipulations on the string data that comes from the controller. In particular, there's a common manipulation (convert from underscore_case to CamelCase) that I'd like to bring out into a separate function. Then later I can use it repeatedly like {% set x = magic(a) ~ magic(b) %}. However I cannot find how to make such a reusable function inside the template itself. There are macros, but those don't seem to be able to return values. Filters are another option that seem to fit the bill, but I can only define those on PHP side.
Can this be done? Or should I do all the advanced string manipulation controller-side? It kinda feels like I'm pulling parts of display logic in there; things that should be in the view.
Twig is for outputting data. If you need to "transform" the data you need to do that before you send it to twig or you need to extend twig
Ideally, all the data you send to twig is just variables and arrays that needs the least amount of manipulation on their own.
When you're actually "in" twig, the data processing can be assumed to be "done" and only needs to be outputted in the appropriate places with minimal logic to decide user interface styles.
So revisit your logic and prepare your data better before sending it to twig.
An example for extending a toolkit class that contains our magic methods to do real wizardry.
class CustomToolkit
{
public function magic_a($a)
{
return strtolower($a); }
public function magic_b($b)
{
return camel_case($b);
}
public function magic_tidle($a, $b)
{
return $this->magic_a($a) ~ $this->magic_b($b);
}
}
Then you add this to your twig instance. I added here a complete instantiation loop. if you have a service provider you can just grab the instance from there and add it to that one.
$twig = new Twig_Environment(new Twig_Loader_Array([
'html' => $contents
]),[
'auto_reload' => true,
'debug' => false,
]);
$twig->addExtension('toolkit', new CustomToolkit ());
echo $twig->render('html', $values);
Then in your twig code you should be able to do something along the lines of
{% set x = toolkit.magic_tidle("value","value_b") %}
You are right, macros do not have return values and you cannot really make them have any. All they do is outputting strings.
Still, you are able to capture string output using set: https://twig.symfony.com/doc/2.x/tags/set.html
The syntax looks similar to this:
{% set var %}
{{ call.macro() }}
{% endset %}
The output of the macro call is then stored inside var. You may want to strip the whitespace though.
But then, consider rethinking what you are doing. Is this still presentation logic, or is your controller simply "too lazy" to transform the strings prior to passing them to twig? If it's really presentation logic, simply adding a twig filter by extending twig surely is worth the hassle. Not only because your code becomes testable.
Can this be done?
Yes! However, Twig templates are not the ideal places to run logic. At least, we should do our best to avoid it. Instead, Controller should return what Twig template needs. Logic should run in Service, Utility, Helper (you name it) etc. and Controller returns it to Twig. Twig then just displays it.
Can twig macros return values?
Yes! Look at this example. It accepts parameters and returns (not a real "return" thing but you get the idea) something back.
Example:
Assuming that the data you are trying to manipulate is something simple.
use Doctrine\Common\Inflector\Inflector;
Controller
{
action() {
$data = Inflector::camelize('hello_world'); // This will become helloWorld
return ....;
}
}
Look into Inflector class. It has useful stuff.
I have the below content in my DB-
<p>This is dummy content for testing</p>
{{LandingPageController::getTest()}}
I want to render that into my view. But when I'm rendering this in Laravel view, this {{LandingPageController::getTest()}} is getting displayed as it is stored in DB.
I want to call the LandingPageController getTest method in my view.
Please suggest me a quick fix for this.
Landing Page Controller
public function getTest(){
return "Hello World!!!";
}
just make the function static
public static function getTest(){
return "Hello World!!!";
}
that's the only way you can call it like this {{LandingPageController::getTest()}} but I do advice not to do that in your blade file this not a good code design. you should do $test = LandingPageController::getTest() in the controller that you return the blade view and pass it like this return view('blade_file_name',compact('test')) and in your blade file just do {{$test}}
PS - if you doing it your controller use the class like this use Path\To\Controller\LandingPageController
Use namespace for that controller in your blade file. example
namespace App\Http\Controllers\LandingPageController;
You can evaluate a string as a php code using the eval() function
eval — Evaluate a string as PHP code
But it is highly discouraged.
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
You can use a generic string, {test} for example, when saving the content in the storage.
<p>This is dummy content for testing</p>
{test}
Then whenever you need to display the actual content, you can simply replace the generic string with the real value. You'll have this line in your blade file:
{{ str_replace('{str}', "Hello World", $content) }}
Take a look at Helper. You can call helper function in view to render your text or html
Got the solution, achieve the functionality with "laravel-shortcodes".
Found a very good tutorial on laravel-shortcodes like wordpress
I've created a bolt extension which provides a new twig function foo. The twig functions is added to the twig framework with the following code $this->addTwigFunction('foo', 'twigFoo');.
public function twigFoo()
{
$markup = '
<hr>
Foo
<hr>';
return new \Twig_Markup($markup, 'UTF-8');
}
My idea was that the users of the cms can use the twig function in the content types. But when the body of a record is displayed the twig function is visible as plain HTML for example: {{ foo }}
I think the problem is, that the twig template will be rendered before the record body will be assigned. So the body of my record will not be evaluated by twig. Has anyone a idea how to evaluate the twig function witch is use in a record? What's the best practice for this problems?
The field in the ContentType needs allowtwig: true to tell Bolt that you trust the field/editor to allow this, e.g.:
body:
type: html
allowtwig: true
The Problem is that Twig does not render Twig inside a Twig variable. You could create an escape function to still do that. Anyway this might not be the best idea to give your CMS users the possibility to use Twig as this gives them full access to your code.
Anyway, here is an escape function that could help you
$this->app['twig']->getExtension('core')->setEscaper('code', function($twigEnv, $string, $charset) {
$twig = clone $this->app['twig'];
$twig->setLoader(new \Twig_Loader_String());
return $twig->render($string);
});
You could then use the twig filter "code" in your template. e.g.:
{{ record.body|escape('code') }}
We got a shopsystem working with Smarty. I need to pass some Smarty variables to a PHP function and get the return.
What I know and also did so far is the following:
{$order_id|#get_order_total}
So this passes the Smarty Variable "$order_id" to a included PHP file which contains the function get_order_total($order_id) and shows me the return of this function.
Now I need to pass 3 variables to a PHP function. The function would for example look like this:
handleDebit($order, $payCode, $insertId)
Sadly i have not found the right thing so far in smarty documentation. Anyone has ever done this?
If you really need to call the function from within smarty templates, register a wrapper function as smarty-plugin:
<?php
$smarty->registerPlugin("function","handleDebit", "handleDebitSmarty");
function handleDebitSmarty($params, $smarty)
{
return handleDebit($params['order'], $params['payCode'], $params['insertId']);
}
Now you can use it as smarty tag:
{handleDebit order=$blah payCode=$blub insertId=$yeahh}
But you should consider #JonSterling s advice and try to find a way auch that a controller is doing the handleDebit-call and you only handle results/display-stuff in the template.
I am working in a symfony app and I need to use a function like the addslashes function in php but I can't find any think like that in twig ? is there any way to do that
You can register PHP's addslashes function as a Twig filter by doing:
$twig = new Twig_Environment($loader);
$twig->addFilter(new Twig_SimpleFilter('addslashes', 'addslashes'));
and then in your twig template use it by doing: {{ var|addslashes }}.
If auto-escaping is enabled, then your filter will be escaped after it is called. If auto-escaping is causing you problems, then take a look at the "automatic-escaping" link below and see how to disable it. It should go without saying--but, if you disable auto-escaping, then you are responsible for sanitizing the data before it is output.
Resources:
http://twig.sensiolabs.org/doc/advanced.html#automatic-escaping
http://twig.sensiolabs.org/doc/advanced.html#filters
Here is the answer
If you are trying to addslashes in HTML code then try
{{ my_variable|e('html') }}
If you are trying to addslashes in JS code then try
{{ my_variable|e('js') }}
If answers works for you then vote the answer.