I'm trying to build a page in Slim that will bring up a subscribers details. I've worked out how to create the route and the relevant method in the controller which all works correctly. I'm using Twig for the views and can't work out how I would access the subscriber from the view.
Route
$app->get('/subscriber/{id}', 'SubscriberController:getSubscriber');
Subscriber controller
public function getSubscriber($request, $response, $args)
{
$subscriber = Subscriber::where('id', $args['id'])->first();
}
I've been using the below in my controller to render my Twig templates
return $this->container->view->render($response, 'subscriber.twig');
How would I pass in or access my subscriber variable in the Twig template? I can't work out how to pass it through?
On the render method the 3. parameter is data where you can give the twig template variables.
$data = ['subscriber' => $subscriber];
return $this->container->view->render($response, 'subscriber.twig', $data);
now you can access this variable inside twig.
Related
To build a sidebar that has a lot of dynamic data on it I learned about View composers in Laravel. The problem was that View Composers trigger when the view loads, overriding any data from the controller for variables with the same name. According to the Laravel 5.4 documentation though, I achieve what I want with view creators :
View creators are very similar to view composers; however, they are
executed immediately after the view is instantiated instead of waiting
until the view is about to render. To register a view creator, use the
creator method:
From what I understand, this means if I load variables with the same name in the controller and the creator, controller should override it. However this isn't happening with my code. The view composer:
public function boot()
{
view()->creator('*', function ($view) {
$userCompanies = auth()->user()->company()->get();
$currentCompany = auth()->user()->getCurrentCompany();
$view->with(compact('userCompanies', 'currentCompany'));
});
}
And here is one of the controllers, for example:
public function name()
{
$currentCompany = (object) ['name' => 'creating', 'id' => '0', 'account_balance' => 'N/A'];
return view('companies.name', compact('currentCompany'));
}
the $currentCompany variable in question, for example, always retains the value from the creator rather than being overridden by the one from the controller. Any idea what is wrong here?
After some research, I realized my initial assumption that the data from the view creator can be overwritten by the data from the controller was wrong. The creator still loads after the controller somehow. But I found a simple solution.
For those who want to use View composers/creators for default data that can get overwritten, do an array merge between the controller and composer/creator data at the end of the boot() method of the composer/creator, like so:
$with = array_merge(compact('userCompanies', 'currentCompany', 'currentUser'), $view->getData());
$view->with($with);
I can access cookie in controller then pass it to view
//HomeController.php
public function index(Request $request)
{
$name = Cookie::get('name');
return view('index', ['name'=> $name]);
}
But I want to write a small control (widget) that can fetch data from cookie without concern of parent controller. For example, header, footer widgets could fetch its own data without main page controller knowing which data is needed.
I can query the data from database by using View Composer. But, how can I access data from view in the request cookie ?
Using static function with defining namespace and etc is a not safe.
Cuz maybe in next versions of framework this namespace can change.
It's better to use helper functions.
{{ request()->cookie('laravel_session') }}
or
{{ cookie('laravel_session') }}
Tested on working app with Laravel 5.2
You can use {{ Cookie::get('laravel_session') }} to print out the cookie inside your view.
You can use
{{\Illuminate\Support\Facades\Cookie::get('laravel_session')}}
in a blade template
You can use:
$response = new \Illuminate\Http\Response(view('your_view'));
$response->withCookie(cookie('cookieName' , 'cookieValue' , expire));
return $response;
or
\Cookie::queue('cookieName', 'cookieValue', expire);
return view('your_view');
I've used both of them.
Hi I want to send single variable to view but I am unable to do it, Please help me.
Controller:
public function src($id=""){
$this->load->view('catsrc', $id);
}
View:
<div class="container">
<?php echo $id ;?>
</div>
Error Getting:
Message: Undefined variable: id
I am not an expert of CodeIgniter but according to official documentation: "Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function"
$this->load->view('catsrc', [ 'id' => $id ]);
was that so hard ?
Happy coding :)
CodeIgniter views read from a $data array. To reference $id in a view, put it in the $data array in your controller
$data = array('id' => 'your_value_here');
and pass $data to the view.
Full documentation on views lives at: https://ellislab.com/codeigniter/user-guide/general/views.html
How CI Classes Pass Information and Control to Each Other
Calling Views
We have seen how the controller calls a view and passes data to it:
First it creates an array of data ($data) to pass to the view; then it loads and calls the view in the same expression:
$this->load->view('testview', $data);
You can call libraries, models, plug-ins, or helpers from within any controller, and models and libraries can also call each other as well as plug-ins and helpers.
However, you can't call one controller from another, or call a controller from a
model or library. There are only two ways that a model or a library can refer back to a controller:
Firstly, it can return data. If the controller assigns a value like this:
$foo = $this->mymodel->myfunction();
and the function is set to return a value, then that value will be passed to the variable $foo inside the controller.
This may not answer your question directly but helps!!
I'm writing a website using Slim Framework and Twig.
The sidebar on the website will have dynamically created links and i want to get the links from the database/cache every time a page is rendered, i can do this in each controller action but i would like to do this in my base template so i don't have to get and render the data manually in every controller action.
I have looked through the twig documentation and I haven't seen anything that could be of use besides the include function/tag but i don't see how i could get the data easily.
Is my only option to write an twig extension to do this or is there an easier way?
First of all: templates usually shouldn't contain any type of bussines logic but only render the data you provide it.
However you could write a custom twig function and use that to aquire the menu data from the DB in order to render it in your base template.
Alternativeley you could write some Slim middleware that aquires the data which might be able to inject the data into the template.
Hope that helps.
After reading Anticoms answer i was able to do it by writing a Twig extension.
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('render', array($this, 'render'))
);
}
public function render($template, $controller, $action) {
$app = Slim::getInstance();
return $app->$controller->$action($template);
}
Now i can simply write
{{ render('Shared/sidebar.twig', 'Controller', 'Index') }}
Into my twig template to render the template with the data i want.
Note that my render() function uses slim dependency injection to instanciate the controller at runtime.
I'm learning Laravel, and for my first project I'd like to create my portfolio. However, the first task I have to do is confusing me.
So I created my templates, layout.blade.php and home.blade.php. That makes sense to me, but now how do I tell Laravel, or how do I route to home.blade.php?
I'm looking for an explanation rather then just code. I'm trying to learn.
Actually, a view in MVC application is just a part of the application and it's only for presentation logic, the UI and one doesn't call/load a view directly without the help of another part (controller/function) of the application. Basically, you make a request to a route and that route passes the control over to a controller/function and from there you show/load the view. So it's not a tutorial site and it's also not possible to explain about MVC here, you should read about it and for Laravel, it's best place to understand the basics on it's documentation, well explained with examples, anyways.
In case of Laravel, you should create a controller/class or an anonymous function in your apps/routes.php file and show the view from one of those. Just follow the given instruction step by step.
Using a Class:
To create a route to your Home Controller you should add this code in your app/routes.php
// This will call "showWelcome" method in your "HomeController" class
Route::any('/', array( 'as' => 'home', 'uses' => 'HomeController#showWelcome' ));
Then create the HomeController controller/class (create a file in your controllers folder and save this file using HomeController.php as it's name) then paste the code given below
class HomeController extends BaseController {
public function showWelcome()
{
// whatever you do, do it here
// prepare some data to use in the view (optional)
$data['page_title'] = 'Home Page';
// finally load the view
return View::make('home', $data);
}
}
If you have {{ $title }} in your home.blade.php then it'll print Home Page. So, to use a view you need a controller or an anonymous function and load the view from the controller/function.
Using an anonymous function:
Also, you can use an anonymous function instead of a controller/class to show the view from directly your route, i.e.
Route::any('/', function(){
// return View::make('home');
// or this
$data['page_title'] = 'Home Page'; // (optional)
return View::make('home', $data);
});
Using this approach, whenever you make a request to the home page, Laravel will call the anonymous function given in/as route's callback and from there you show your view.
Make sure to extend the the master/main layout in sub view (home):
Also, remember that, you have following at the first line of your home.blade.php file
#extends('layouts.layout')
It looks confusing, you may rename the main layout (layout.blade.php) to master.blade.php and use following in your home.blade.php instead
#extends('layouts.master')
Read the doc/understand basics:
You should read Laravel's documentation properly, (check templates to understand blade templating) and also read some MVC examples, that may help you too understand the basics of an MVC framework (you may find more by googling) and some good posts about MVC on SO.
Check it routing in Laravel.
You need to use route file and controllers
Create needed function in your Controller file and create a template file for example
class UserController extends BaseController {
/**
* Show the profile for the given user.
*/
public function showProfile($id)
{
$user = User::find($id);
return View::make('user.profile', array('user' => $user));
}
}
you need to create view file views/user/profile.blade.php
View::make('user.profile', array('user' => $user)) == views/user/profile.blade.php
And you should read it http://laravel.com/docs/responses and also this http://laravel.com/docs/quick#creating-a-view