Laravel Views (creator & make) - php

I made an view called (head.blade.php) and tried to load it in HomeController __construct function with View::make() function. However, the function works, but not with the variables.
For example, here's function, with View::make():
public function __construct() {
$this->asset = new Asset;
$assets = array('core');
$css = $this->asset->generate($assets);
return View::make('includes.head')->with('styles', $css);
}
If I try to use $styles variable in view, it gives me error: (Undefined variable $styles in...-)
But, digging in Laravel docs I have found this method:
public function __construct() {
$this->asset = new Asset;
$assets = array('core');
$css = $this->asset->generate($assets);
View::creator('includes.head', function($view) use ($css) {
$view->with('styles', $css);
});
}
And the method View::creator works.
My question is, how and why the View::make() doesn't work in __construct?
PS. I'm calling the view in another view with #include method.

In general OOP, you do not return any value from a constructor. The implicit return value of a constructor is the object. Remember that the constructor is called whenever a new object is made:
$myObject = new MyObject(); // <-- I just called the MyObject constructor
Instantiation of a Laravel controller happens prior to the dispatching of the route, so returning the View inside the constructor is logically incorrect. See also this answer.
I'm not sure why you're trying to do this, but I believe it could be because you're trying to attach a 'header' view to all of the views returned by this specific controller. If so, this isn't the way you do this in Laravel. To accomplish that, make a layout view that your other views will extend:
<!-- app/views/layout/master.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<article>
#include('layout.header')
#yield('content')
#include('layout.footer')
</article>
</body>
</html>
<!-- app/views/layout/header.blade.php -->
<header>
A Header
</header>
<!-- app/views/layout/footer.blade.php -->
<footer>
A Footer
</footer>
<!-- app/views/some-view.blade.php -->
#extends('layout.master')
#section('content')
View Content
#stop
With this setup, some-view.blade.php will have both a header and a footer sandwiching the view's main content.

Related

Laravel Blade return output of a "route name", not the URI

I have this footer inside a blade template. This footer should be displaying a variable dynamically inside the said template.
template.blade.php
<html>
<body>
#include('templates.usermenu.usermenu')
#include("templates.navigation.navigation")
#yield('header')
#yield('content')
{{ route('footer-links') }} <--this is the footer. this only outputs the "URI"
</body>
</html>
here is the output of the code above
Here is the footer.blade.php with a variable that should be displayed:
footer.blade.php
{{-- buttons --}}
#foreach ($footerLinksRecord as $record)
<div class="clearfix">
<a class="poppins-medium text-md button-white text-left float-left clickable" href="{{ $record->link }}">{{ $record->name }}
</a>
</div>
#endforeach
The footer.blade.php needs to output a variable coming from its FooterLinksController#index (the template.blade.php does not have any controller managing it).
Here is the route for the footer.blade.php and the home.index (home.index calls the template.blade.php inside its code):
Route::get('/', function () {
return view('home.index');
})->name('home');
// Footer Links Index
Route::get('/footer', [FooterLinksController::class, 'index'])->name('footer-links');
Here is the FooterLinksController#index:
public function index()
{
$footerLinksRecord = FooterLinks::all();
return $footerLinksRecord;
}
What should happen is that the footer.blade.php should output the data of its route when called, not the URI.
How should this be approached?
edit removed #include. I'm looking at the wrong code.
You could use a View Composer to handle the data for the footer view. You can include the footer where needed without worrying about the data needed for it.
You can create a new Service Provider or add to the boot method of an existing one:
public function boot()
{
...
View::composer('footer', FooterComposer::class);
}
You can use a class with a compose method to handle composing the view instead of a Controller:
class FooterComposer
{
...
public function compose($view)
{
$view->with('footerLinksRecord', FooterLinks::all());
}
}
In the layout, template.blade.php, you only have to 'include' the footer:
#include('footer')
You also have the option of making a Blade component for the footer instead.
Laravel 8.x Docs - Views - View Composers
Laravel 8.x Docs - Blade - Components

Autoload a view on every page with codeigniter

So I have my views split up basically between three (3) files:
-- Header file
$this->load->view('templates/header', $data);
-- Main Body file
$this->load->view('login_view', $data);
-- Footer file
$this->load->view('templates/footer', $data);
Now I just recently started building, but I've noticed it's really annoying to retype the header and footer on every controller to tell it to load. Is there a way to automatically load the header and footer view on every request?
I found an article long time ago, but i can't seem to find it now, basically the author, (which i forgot) override the showing of output. this method of output will access your views regarding the given controller/method and will try to search in your views directory automatically.
Use at your own risk
Application/core/MY_COntroller.php
----------------------------------------------------------------------------
class MY_Controller Extends CI_Controller
{
protected $layout_view = 'layouts/application'; // default
protected $content_view =''; //data
protected $view_data = array(); //data to be passed
public function __construct()
{
parent::__construct();
}
public function _output($output)
{
if($this->content_view !== FALSE && empty($this->content_view)) $this->content_view = $this->router->class . '/' . $this->router->method;
$yield = file_exists(APPPATH . 'views/' . $this->content_view . EXT) ? $this->load->view($this->content_view, $this->view_data, TRUE) : FALSE ;
if($this->layout_view)
{
$html = $this->load->view($this->layout_view, array('yield' => $yield), TRUE);
echo $html;
}
}
}
Application/views/layouts/layout.php
----------------------------------------------------------------------------
<html>
<head>
<title>master layout</title>
</head>
<body>
<!-- this variable yeild is important-->
<div><?=$yield;?></div>
</body>
</html>
This is what i use to create my template. Basically you need a directory structure as follows.
+Views
|+layouts
||-layout.php
the layout.php will serve as your master template
How to use?
extend the controller
class User Extends MY_Controller
{
public function create_user()
{
//code here
}
public function delete_user()
{
//use a different master template
$this->layout_view = 'second_master_layout';
}
public function show_user()
{
//pass the data to the view page
$this->view_data['users'] = $users_from_db;
}
}
Just create directory in your views and name it with the controller name i.e user then inside it add a file you named your method i.e create_user
So now your Directory structure would be
+Views
| +layouts
| |-layout.php
| |-second_master_layout.php
| +user
| |-create_user.php
Just Edit the code to give you a dynamic header or footer
Here is the simple example which i always do with my CI project.
Pass the body part as a $main variable on controller's function
function test(){
$data['main']='pages/about_us'; // this is the view file which you want to load
$data['something']='some data';// your other data which you may need on view
$this->load->view('index',$data);
}
now on the view load the $main variable
<html lang="en">
<head>
</head>
<body>
<div id="container">
<?php $this->load->view('includes/header');?>
<div id="body">
<?$this->load->view($main);?>
</div>
<?php $this->load->view('includes/footer');?>
</div>
</body>
</html>
In this way you can always use index.php for your all the functions just value of $main will be different.
Happy codeing
Using MY_Controller:
class MY_Controller extends CI_Controller {
public $template_dir;
public $header;
public $footer;
public function __construct() {
parent::__construct();
$template_dir = 'templates'; // your template directory
$header = 'header';
$footer = 'footer';
$this->template_dir = $template_dir;
$this->header = $header;
$this->footer = $footer;
}
function load_views ($main, $data = [], $include_temps = true) {
if ($include_temps = true) {
$this->load->view('$this->template_dir.'/'.$this->header);
$this->load->view($main);
$this->load->view('$this->template_dir.'/'.$this->footer);
} else {
$this->load->view($main);
}
}
}
Then load it like: $this->load_views('login_view', $data);
You can do with library.
Create a new library file called template.php and write a function called load_template. In that function, use above code.
public function load_template($view_file_name,$data_array=array()) {
$ci = &get_instatnce();
$ci->load->view("header");
$ci->load->view($view_file_name,$data_array);
$ci->> load->view("footer");
}
You have to load this library in autoload file in config folder. so you don't want to load in all controller.
You can call
$this->template->load_template("index",$data_array);
If you want to pass date to view file, then you can send via $data_array
There is an article on this topic on ellislab forums. Please take a look. It may help you.
http://ellislab.com/forums/viewthread/86991/
Alternative way: Load your header and footer views inside the concern body view file. This way you can have batter control over files you want to include in case you have multiple headers and footer files for different purposes. Sample code shown below.
<html lang="en">
<head>
</head>
<body>
<div id="container">
<?php $this->load->view('header');?>
<div id="body">
body
</div>
<?php $this->load->view('footer');?>
</div>
</body>
</html>

Conditional extends in Blade

Is there any way to do a conditional #extends statement in the Blade templating language?
What I've tried:
#if(!Request::ajax())
#extends('dashboard.master')
#section('content')
#endif
<div class="jumbotron">
Hey!
</div>
#if(!Request::ajax())
#stop
#endif
Output
When the request was not AJAX it printed out #extends('dashboard.master'), but the AJAX request worked fine.
What I'm trying to do
Stop including the master template (which includes header and footer) for AJAX so it can easily display the requested content
#extends((( Request::ajax()) ? 'layouts.ajax' : 'layouts.default' ))
in the master layout:
#if(!Request::ajax())
//the master layout with #yield('content'). i.e. your current layout
#else
#yield('content')
#endif
This kind of logic should really be kept out of the template.
In your controller set the $layout property to be dashboard.master then instead of calling returning your view or response, terminate with just $this->layout->content = View::make('dashboard.template')
Take a look at the Laravel docs on this
You could end up with something like this
<?php
class Something extends BaseController {
$layout = 'dashboard.master';
public function getIndex()
{
$template = View::make('dashboard.template');
if(Request::ajax()) {
return $template;
}
$this->layout->content = $template;
}
}

Zend Framework 2 - Wrapping $this->content with another layout

I am trying to create a wrapper for the $this->content of a specific Module.
What I have is a main layout (All the modules will follow this layout) which builds the base layout with headers and footers, etc. These will stay the same across all the Modules.
However I want to have modules with a custom layout for their body content. I.e. for custom nav bars, etc.
So with the following structure:
module
/ ModuleName
/ view
/ layout
/ modulelayout.phtml
/ modulename
/ index
/ index.phtml
view
/ layout
/ layout.phtml
The /view/layout/layout.phtml:
<?= $this->doctype(); ?>
<html lang="en">
<head>
...
</head>
<body>
<header>...</header>
<div id='body'>
<?= $this->content; ?>
</div>
<footer>...</footer>
</body>
</html>
The /module/ModuleName/view/layout/modulelayout.phtml:
<div>...</div>
<div>
<?= $this->content; ?>
</div>
The /module/ModuleName/view/modulename/index/index.phtml:
Hello World
...
So I want all of the actions inside of ModuleName (their $this->content that is displayed), to be wrapped with the layout from modulelayout.phtml.
I created a listener on the dispatch event of a controller to capture it for all controller actions:
public function onBootstrap($e) {
$app = $e->getApplication();
$app->getEventManager()
->getSharedManager()
->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', array($this, 'dispatchControllerStrategy'));
}
Now I need to know how to I retain the base layout, and add my module layout as a wrapper?
public function dispatchControllerStrategy($e) {
$controller = $e->getTarget();
$layout = $controller->layout();
$wrapper = new ViewModel();
$wrapper->setTemplate('layout/modulelayout');
$layout->addChild($wrapper, 'content');
}
^^^ The adding of the child layout does not seem to wrap $this->content in any way, and the child layout does not render. To bring it all together, this is what I expect the final source to look like:
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
<header>...</header>
<div id='body'>
<div>...</div>
<div>
Hello World
...
</div>
</div>
<footer>...</footer>
</body>
</html>
Thanks!
Well after a lot of messing around I finally found my solution. And it appears that comment of SlmThreeStepView user2257808 was what I wanted to begin with, but my solution fit my need exactly so I am just going to share it here:
I stopped worrying about trying to modify the layout on controller dispatch and focused on the View with the EVENT_RENDERER_POST event:
->attach('Zend\View\View', \Zend\View\ViewEvent::EVENT_RENDERER_POST, array($this, 'renderViewStrategy'));
I then modify my model on render:
private $renderdedOuterView = false;
public function renderViewStrategy($e) {
if ($this->renderdedOuterView) {
return;
} else {
$this->renderdedOuterView = true;
}
$layout = $e->getModel();
$children = $layout->getChildren();
$layout->clearChildren();
$wrapper = new ViewModel();
$wrapper->setTemplate('layout/modulelayout');
$wrapper->addChild($children[0], 'content');
$layout->addChild($wrapper, 'content');
}
I used $renderedOuterView to only do any render modification for the main layout.
Then for the main layout, I get the Model, and grab the attached child which would be the layout for the current action.
I then clear the main template of that child and add my wrapper in its place. Then as a child of my wrapper, I add the layout for the current action I had just removed from the main template.
My not be the best option, but this solution fits exactly what I was trying to accomplish with my question.
UPDATE
I wanted to add that I found out another issue.
All the onBootstraps for each Module get called, regardless if they are the active module.
This was causing a different module to get this layout. The change was adding an EVENT_DISPATCH first:
$evtMgr = $e->getApplication()->getEventManager();
$evtMgr->attach(MvcEvent::EVENT_DISPATCH, array($this, 'handleEventStrategy'));
Then inside of the handleEventStrategy, I check to make sure that the active Module is the module's bootstrap that is being called. If it is, then I attach the EVENT_RENDER_POST and use the renderViewStrategy that I had defined.
If the active module is not the module with the render view strategy, the if condition will fail and no other module will get that modified layout.
Did you try this module: https://github.com/EvanDotPro/EdpModuleLayouts
And then add the config in your module config file
array(
'module_layouts' => array(
'ModuleName' => 'layout/some-layout',
),
);

Manually rendering Zend_View with layout enabled

I'm creating a mail service within my application that has the body of the email stored in the database prior to sending it out to recipients.
Each mail body is a partial view script that has the necessary parameters injected into it via Zend_View.
What I want to do is create a 'mail' layout that can wrap around each of these partials,
but I can only seem to get either the layout content or the view content; not both at once.
What I've got
$scriptPath = 'test_mail';
$view = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('view');
$view->setScriptPath(APPLICATION_PATH . '/modules/mail/views/scripts/partials/');
$view->layout()->setLayout('mail');
var_dump($view->layout()->render($scriptPath));
However, all I receive is the view script content.
My layout is looking something like this:
<table class="mail">
<!-- Snip -->
<?php echo $this->layout()->content; ?>
<!-- Snip -->
</table>
I know this is possible. I don't want to do:
$layout->content = $view->render($scriptPath);
I assume I'm going the wrong way about this. Is it that I need/ don't have the layout controller plugin registered and somehow need to trigger this to get the output?
I suppose I could just create a custom layout class and take care of the rendering myself but wanted to see what others said first.
Any tips? Thanks!
I am using email layout, multiple view templates for different kinds of emails and extended Zend_Mail class for setting desirable body:
class MyMail extends Zend_Mail
{
public function setBodyView($script, $params = array())
{
$layout = new Zend_Layout(array('layoutPath' => APPLICATION_PATH . '/layouts/scripts'));
$layout->setLayout('email'); // Your email layout
$view = new Zend_View();
$view->setScriptPath(APPLICATION_PATH . PATH_TO_MAIL_TEMPLATES);
foreach ($params as $key => $value) {
$view->assign($key, $value);
}
$layout->content = $view->render($script . '.phtml');
$html = $layout->render();
$this->setBodyHtml($html);
}
}
I using %mail_body% pattern in my mail template.
$layout = Zend_Layout::getMvcInstance();
$view = $layout->getView();
$mail_template = $view->render('template.phtml');
$returnYourReadyTemplate = str_replace('%mail_body%', $mail_body, $mail_template);
in template.phtml :
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body >
<div style="margin:30px 20px 10px 20px">
%mail_body%
</div>
</body>
</html>
Hope this helps you!

Categories