i would put a controller for my navbar and i would use a query to get a variable from my database..
I don't have a controller and i create it in this way:
<?php
namespace Dt\EcBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class NavbarController extends Controller {
public function navbarAction(Request $request) {
$prova = "ciao";
return $this->render('DtEcBundle:Header:navbar.html.twig',array(
"prova" => $prova,
));
}
}
Now i put my render controller in the body of : "{# app/Resources/views/base.html.twig #}"
{{ render(controller('DtEcBundle:Navbar:navbar', { 'prova': prova })) }}
I follow this but i don t understand the error: "http://symfony.com/doc/current/book/templating.html#embedding-controllers"
I Get this error Variable "prova" does not exist in DtEcBundle:Header:navbar.html.twig at line 5 but if i write the code in navbar.html.twig give me equals error..
If i remove the variable and i write only
{{ render(controller('DtEcBundle:Navbar:navbar')) }}
Give me a server error number 500 o.o..
How can i do for use my controller only in navbar.html.twig??
navbarAction doesn't take prova variable as a parameter, so why are you passing it there in a base template?
I think that action should fetch these data from db.
In that case, using:
{{ render(controller('DtEcBundle:Navbar:navbar')) }}
seems to be ok, and error is somewhere else.
If you get a 500, check logs to tell us what's exactly wrong.
And format your code, it's barely readable.
The error is the code:
{{ render(controller('DtEcBundle:Navbar:navbar', { 'prova': prova })) }}
the prova variable doesn't exists in twig, the controller is fine.
I if you want put the var from twig to controller:
/**
* #Route("/prova/{prova}", name="prova")
*/
public function navbarAction(Request $request,$prova) {
return $this->render('DtEcBundle:Header:navbar.html.twig',array(
"prova" => $prova,
));
}
and twig:
{% set prova = 'foo' %}
{{ render(controller('DtEcBundle:Navbar:navbar', { 'prova': prova })) }}
Related
I just start to learning Laravel, I stuck in a part, I want to get data from database and pass it to a blade (view) file then use this view in another view file, and want to pass one variable to a controller but I got this error:
"Class 'adsController' not found"
web.php
Route::get('seller/panel', 'sellerController#panel');
panel.blade.php
#include('seller\hook\ads')
sellerController.php
public function panel(){
$ads = DB::table('ads')->get();
return view('hook\ads', ['ads' => $ads]);
}
adsController.php
class adsController extends Controller {
public function getStatus($p) {
if ($p == 'something') {
$status = 'yeah';
} else {
$status = 'blah blahe';
}
return view('hook\ads', $status);
}
}
ads.blade.php
<div class="ads">
#foreach ($ads as $ad)
{{ $ad->name }}
{{ adsController::getStatus($ad->approved) }}
#endforeach
</div>
So, as you see I am tring to get data from database in sellerController.php then pass it to ads.blade.php then I want to use adsController.php 's function in ads.blade.php, but it can't find adsController
Sorry I am newbie to laravel
As everyone said, it's not recommended to call the controller from the view.
Here's what I would do :
In your model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ad extends Model{
public function getStatus()
{
return $this->approved == 'something' ? 'yeah' : 'blah blaehe';
}
}
In your view :
<div class="ads">
#foreach ($ads as $ad)
{{ $ad->name }}
#include('hook.ads', ['status' => $ad->getStatus()])
#endforeach
</div>
In your controller :
public function panel(){
$ads = \App\Ad::all();
return view('hook\ads', ['ads' => $ads]);
}
At the beginning of the blade file you could include the following
#php
use App\Http\Controllers\adsController as adsController;
#endphp
then on your blade template you could use the controller as you have used here.
But it is a really bad habit to use one directly.
Since you are a newbie to Laravel change that coding practice.
You could use a service provider of a sort if you want that data which needs to be shown on a particular blade view all the time.
You should try this despite I don't recommend the approach you are trying to achieve.
{!! app('App\Http\Controllers\adsController')->getStatus($ad->approved) !!}
It should work but that's very wrong.
Most often when you get this error when your namespace declaration in the controller is wrong. Typical scenario is where you generate controller stub with Artisan and then move it somewhere else from the default location.
In some cases you need to run:
composer dumpautoload
To generate new optimized class loader map.
Page code:
{% partial 'content/main' %}
Partial:
[services]
{% component 'services' %}
Component:
public function prepareVars()
{
$this->page['servicesList'] = $this->getProperty(); // function returns 123
}
Component template:
{{ servicesList }} //does not display anything =(
Why is not the variable being passed?
Hmm seems something odd, not sure about your onRun method in component
prepareVars will not call automatically we need to call it manually.
did you add prepareVars inside onRun as when page life-cycle called , onRun is called automatically so we need to add prepareVars there as well, so its code get executed.
public function onRun()
{
$this->prepareVars();
}
public function prepareVars()
{
$this->page['servicesList'] = $this->getProperty(); // function returns 123
}
if you are already doing this then please notify it in comment so we can look further.
I cannot figure out how to display the route name in the blade template of laravel. Please find below the sample code. Thank you.
from the controller (StaffsController.php)
public function index()
{
$thisRoute = Route::current()->uri();
return view('staff.list')>with(compact('thisRoute'));
}
Blade:
{{ $thisRoute }}
This is the var_dump
/home/vagrant/Code/spark/app/Http/Controllers/StaffsController.php:20:string 'staffs' (length=6)
Error:
(1/1) UnexpectedValueException
The Response content must be a string or object implementing __toString(), "boolean" given.
When i change the code in the controller to:
public function index()
{
$thisRoute = Route::current()->uri();
return dd($thisRoute);
}
I get "staffs" as output which is correct which is a string from the dump, right?
change your return statement to be like this :
return view('staff.list', compact('thisRoute'));
if you are using laravel 5.3 or above you can get route name like this:
Route::currentRouteName();
with this, you really don't have to passe it from your controller to the view just use it directly from your blade view :
{{ Route::currentRouteName() }}
Sorry guys, I solved the issue. I missed - in the line
return view('staff.list')>with(compact('thisRoute'));
Changed it to
return view('staff.list')->with(compact('thisRoute'));
I made a mistake.
Thank you
I have this controller where \Exception is raised (I haven't figured out which SF2 Exception to use yet) upon certain condition. Here is it:
<?php
namespace My\AppBundle\Controller;
use ....
class MyController extends Controller
{
const EXCEPTION_MESSAGE = <<<EOF
My <b>HTML</b>
<br/>
<small>Small phrase</small>
EOF;
public function indexAction()
{
// my logic
if(in_array($data, $array))
throw new \Exception(self::EXCEPTION_MESSAGE);
// the rest of my logic
return ....
}
}
And in app/Resources/TwigBundle/views/Exception/error.html.twig
{% extends '::base.html.twig' %}
{% block body %}
<h2>Error</h2>
<p>{{ exception.message }}</p>
{% endblock %}
The problem is HTML is not rendered when seeing the error page in prod environement.
I tried {{ exception.message|raw }} and also setting autoescape to false as per this answer but it seems to have no effect.
How can I do to make HTML works when displaying the \Exception message in Twig?
Where ever in the code you catch the exception is where it is needed to be added to the array you pass to twig. for example
$vars = [];
try {
$a->indexAction();
//fill $vars
} catch (Exception $e) {
$vars['exception'] = $e;
}
//pass $vars to twig
I want to have a URL that returns a simple JSON object. I am trying to use Twig to generate the JSON object:
{
"urls": [
{% for child in page.root %}
"{{ child.url }}"{% if not loop.last %},{% endif %}
{% endfor %}
]
}
The carriage returns will not remain in place though, and I keep getting a result that looks like this:
{'urls':['../ants/','../brick-report/','../the-pollution-intervention/','../barclay/','../broken-advertising/','../aldat-n-densom/','../thisisart/','../there-she-goes-again/']}
which Jquery will not parse with it's ajax or getJSON methods. It's totally ignoring this JSON. How might I convince Twig to put the right whitespace in place? I've looked at the manual and it only seems concerned with NOT inserting whitespace.
This works for me (twig template):
var parsedJSON = JSON.parse('{{ ['one', 'two', 'three']|json_encode|e('js') }}');
And this:
console.log(parsedJSON);
outputs:
Array ["one", "two", "three"]
in browser's console.
Twig has a filter for this.
json_encode, it uses PHP json_encode function.
for your case:
{{ {'urls': page.root}|json_encode }}
will output
{"urls":["..\/ants\/","..\/brick-report\/","..\/the-pollution-intervention\/","..\/barclay\/","..\/broken-advertising\/","..\/aldat-n-densom\/","..\/thisisart\/","..\/there-she-goes-again\/"]}
the code is tested and works. For more information take a look at the Twig Documentation for json_encode.
Generally it would make more sense to make controller return json directly, by returning JsonRespnse object
But if you really need to output JSON in Twig and assign it to variable, you can also use:
let foo = {{ bar|json_encode|raw }}
Don't use Twig to generate your json response.
In your controller, use:
return new Response(json_encode($var));
Sample:
public function sampleAction()
{
$urls = array('../test', '../something', '../sample');
return new Response(json_encode($var));
}
If URLs are generated from Symfony2 routes, you can use:
public function sampleAction()
{
$urls = array(
$this->generateUrl('my_test'),
$this->generateUrl('my_something'),
$this->generateUrl('my_sample'),
);
return new Response(json_encode($var));
}
Try wrapping your template in an autoescape block:
{% autoescape 'js' %}
{ "href": "{{ my_url }}" }
{% endautoescape%}
Thats easy if you extend twig.
First, create a class that will contain the extension:
<?php
namespace Acme\DemoBundle\Twig\Extension;
use Symfony\Component\DependencyInjection\ContainerInterface;
use \Twig_Extension;
class VarsExtension extends Twig_Extension
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getName()
{
return 'some.extension';
}
public function getFilters() {
return array(
'json_decode' => new \Twig_Filter_Method($this, 'jsonDecode'),
);
}
public function jsonDecode($str) {
return json_decode($str);
}
}
Basically the $.getJson() method requires json but ther is a string
so you can use $.get() to get the response and use the parser to parse the string to JSON
$.get("ffff",function(data){
// user parser
JSON.parse();
});