Is there any way to load view 'header'/'footer' without calling $this->load->view('header') or $this->load->view('footer') in every controller? Maybe a template that can be use in every view?
Here are a couple simple approaches to get you started:
Create a template class:
class Template {
function load($view)
{
$CI = &get_instance();
$CI->load->view('header');
$CI->load->view($view);
$CI->load->view('footer');
}
}
Usage in controller:
$this->template->load('my_view');
Use a master view file:
<!-- views/master.php -->
<html>
<header>Your header</header>
<?php $this->load->view($view, $data); ?>
<footer>Your footer</footer>
</html>
In the controller:
$this->load->view('master', array(
'view' => 'my-view-file',
'data' => $some_data
));
I prefer the Template class approach, as it's easy to add methods to append templates areas, load javascript files, and whatever else you need. I also prefer to automatically select the view file based on the method being called. Something like this:
if ( ! isset($view_file)) {
$view_file = $CI->router->fetch_class().'/'.$CI->router->fetch_method();
}
This would load views/users/index.php if the controller is Users and the method is index.
You need to load view files somehow, this the way CI use to include the files.
Stick to the standard, I think it's the best practice.
Make a function that loads header and footer and places data in between.
Anyway the model on which CI is built requires the explicit loading of views (afaik).
I usually extend CI's Loader class to accomplish this...
<?php
class MY_Loader extends CI_Loader {
public function view($view, $vars = array(), $return = FALSE, $include_header = TRUE, $include_footer = TRUE)
{
$content = '';
if ($include_header)
{
$content .= parent::view('header', $vars, $return);
}
$content .= parent::view($view, $vars, $return);
if ($include_footer)
{
$content .= parent::view('footer', $vars, $return);
}
return $content;
}
}
Related
I keep rereading the symfony 4 documentation to try to generate twig template with the console commands but I did not find a command . Is there any one know a bundle to generate twig template with console commands ?
I'm solved
class SendEmailNotify extends Command
{
private $container;
private $twig;
private $mailer;
public function __construct($name = null, \Psr\Container\ContainerInterface $container, \Swift_Mailer $mailer)
{
parent::__construct($name);
$this->container = $container;
$this->twig = $this->container->get('twig');
$this->mailer = $mailer;
}
I checked it and the sad answer is no. The list of maker commands is available here. You can even make a twig extension, but not a view. It is worth submitting to them I think.
I needed Twig functionality to send emails from my custom console command.
This is the solution I came up with.
First I installed Twig.
composer require "twig/twig:^2.0"
Then created my own twig service.
<?php
# src/Service/Twig.php
namespace App\Service;
use Symfony\Component\HttpKernel\KernelInterface;
class Twig extends \Twig_Environment {
public function __construct(KernelInterface $kernel) {
$loader = new \Twig_Loader_Filesystem($kernel->getProjectDir());
parent::__construct($loader);
}
}
Now my email command looks like this.
<?php
# src/Command/EmailCommand.php
namespace App\Command;
use Symfony\Component\Console\Command\Command,
Symfony\Component\Console\Input\InputInterface,
Symfony\Component\Console\Output\OutputInterface,
App\Service\Twig;
class EmailCommand extends Command {
protected static $defaultName = 'mybot:email';
private $mailer,
$twig;
public function __construct(\Swift_Mailer $mailer, Twig $twig) {
$this->mailer = $mailer;
$this->twig = $twig;
parent::__construct();
}
protected function configure() {
$this->setDescription('Email bot.');
}
protected function execute(InputInterface $input, OutputInterface $output) {
$template = $this->twig->load('templates/email.html.twig');
$message = (new \Swift_Message('Hello Email'))
->setFrom('emailbot#domain.com')
->setTo('someone#somewhere.com')
->setBody(
$template->render(['name' => 'Fabien']),
'text/html'
);
$this->mailer->send($message);
}
}
This instruction will make a Controller without a twig template
php bin/console make:controller --no-template
Surprisingly this instruction will make a Controller and a template file and subdirectory
php bin/console make:controller
Hello I am new in OpenCart and I am studying it now for my next project. And My first step in learning this framework? is to display my own page using a link from my navigation menu in admin area. But I am getting this error.
Notice: Error: Could not load template C:\wamp\www\myshop/admin/view/template/locations/countries_list.tpl! in C:\wamp\www\myshop\system\engine\controller.php on line 90
And I can't spot my error. Here's what I did.
Here's my controller /controller/locations/countries.php
<?php
class ControllerLocationsCountries extends Controller {
private $error = array();
public function index() {
$this->language->load('locations/countries');
$this->document->setTitle($this->language->get('heading_title'));
$this->getList();
}
protected function getList() {
$this->data['heading_title'] = $this->language->get('heading_title');
$this->template = 'locations/countries_list.tpl';
$this->response->setOutput($this->render());
}
}
Here's my simple view /view/template/locations/countries_list.php
<h1>Hello</h1>
Then in my header I include this code for displaying a link in menu navigation /controller/common/header.php
$this->data['text_locations'] = $this->language->get('text_locations');
....
$this->data['locations'] = $this->url->link('locations/countries', 'token=' . $this->session->data['token'], 'SSL');
That's all. I don't know what part is wrong. Can you help me with this?
The error is pretty self explanatory. The template file doesn't exist. Make sure the template filename and path is exactly the same and that you're using .tpl as the extension and not .php. It's also possible there could be a permissions error, but on WAMP that's not likely
I made a controller to provide some webservices in JSON and i would like to provide some errors informations when Symfony throw an exception ( Error 500 ) , how can i write such a thing ?
The main purpose of the webservice is to update informations in Symfony DB provided by the caller in POST values.
in my controller i return response in JSON and i would like to handle Symfony exception ( like when the values provided or not fitting the schema designed ) to return details informations about errors .
i thought about making a test of every values but it would be a long time to write and not e easy code to read or using a try / catch system , but i think Symfony already provide such a function .
What do you think ?
Thx :)
I think you should use an EventListener to catch errors and return the proper response.
You can place it inside your SomethingBundle/EventListener folder and also you need to define a service in order to be loaded by Symfony.
More info: Event Listener
I hope I helped you, if you think I might be wrong, let me know. Good luck!
EDIT
If you only want to catch the errors inside a specific controller (for example) a controller called Webservice inside your SomethingBundle, you must check it before doing anything:
public function onKernelException(GetResponseForExceptionEvent $event)
{
$request = $event->getRequest();
if($this->getBundle($request) == "Something" && $this->getController($request) == "Webservice")
{
// Do your magic
//...
}
}
private function getBundle(Request $request)
{
$pattern = "#([a-zA-Z]*)Bundle#";
$matches = array();
preg_match($pattern, $request->get('_controller'), $matches);
return (count($matches)) ? $matches[0] : null;
}
private function getController(Request $request)
{
$pattern = "#Controller\\\([a-zA-Z]*)Controller#";
$matches = array();
preg_match($pattern, $request->get('_controller'), $matches);
return (count($matches)) ? $matches[1] : null;
}
DANGER This code is not tested, is only an approach for you to build your own code. But, if I have something wrong on it, tell me. I'd like to keep my examples clean.
Use JsonResponse Symfony class in sandbox:
use Symfony\Component\HttpFoundation\JsonResponse;
$data = array(); // array of returned response, which encode to JSON
$data['error_message'] = 'Bad request or your other error...');
$response = new JsonResponse($data, 500); // 500 - response status
return $response;
Its my first time to use web service in iOS.
REST was my first choice and I use code igniter to form it.
I have my Controller:
require APPPATH.'/libraries/REST_Controller.php';
class Sample extends REST_Controller
{
function example_get()
{
$this->load->helper('arh');
$this->load->model('users');
$users_array = array();
$users = $this->users->get_all_users();
foreach($users as $user){
$new_array = array(
'id'=>$user->id ,
'name'=>$user->name,
'age'=>$user->age,
);
array_push( $users_array, $new_array);
}
$data['users'] = $users_array;
if($data)
{
$this->response($data, 200);
}
}
function user_put()
{
$this->load->model('users');
$this->users->insertAUser();
$message = array('message' => 'ADDED!');
$this->response($message, 200);
}
}
, using my web browser, accessing the URL http://localhost:8888/restApi/index.php/sample/example/format/json really works fine and gives this output:
{"users":[{"id":"1","name":"Porcopio","age":"99"},{"id":"2","name":"Name1","age":"24"},{"id":"3","name":"Porcopio","age":"99"},{"id":"4","name":"Porcopio","age":"99"},{"id":"5","name":"Luna","age":"99"}]}
, this gives me a great output using RKRequest by RestKit in my app.
The problem goes with the put method. This URL :
http://localhost:8888/restApi/index.php/sample/user
always give me an error like this:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<xml>
<status/>
<error>Unknown method.</error>
This is my Users model
<?php
class Users extends CI_Model {
function __construct()
{
parent::__construct();
}
function get_all_users()
{
$this->load->database();
$query = $this->db->get('users');
return $query->result();
}
function insertAUser(){
$this->load->database();
$data = array('name'=> "Sample Name", 'age'=>"99");
$this->db->insert('users', $data);
}
}
?>
What is the work around for my _put method why am I not inserting anything?
Thanks all!
Unless you set the method to PUT or POST, your web server is not going to treat it as such. When you enter URLs in a browser bar, that is almost always a GET request. You might try to use curl like
curl -X POST -d #filename http://your.url.path/whatever
Another link would be: https://superuser.com/questions/149329/what-is-the-curl-command-line-syntax-to-do-a-post-request
So you should be able to do a PUT similarly (perhaps with no data). Not really sure if this should be iOS tagged though :)
I got this problem by using Firefox plug in rest Client.
I just have to indicate the headers and the body to make put and post work.
Please some one tell me how can I position modules like slider or banner in header or how can we define additional regions for the modules.
Well, I am working on it.
Firstly, you should add a new position in the admin page.
Which means you should change three files and add some lines into each.
For example, if you want to add slideshow into header, you should add a new position in
$this->data['text_header'] = $this->language->get('text_header'); // in admin/controller/slideshow.php
////////////////////////////////////////////////
$_['text_header'] = 'Header'; // in admin/language/slideshow.php
////////////////////////////////////////////////
<?php if ($module['position'] == 'header') { ?> // in admin/view/slideshow.tpl
<option value="header" selected="selected"><?php echo $text_header; ?></option>
<?php } else { ?>
<option value="header"><?php echo $text_header; ?></option>
<?php } ?>
Then a new position for slideshow has been defined. and you can choose it in the admin page.
After that, you should add those codes in catalog/view/header.tpl
<?php foreach ($modules as $module) { ?>
<?php echo $module; ?>
<?php } ?>
Then, in the catalog/controller/header.php, add some codes like content_top.php does:
$layout_id = 1;
$module_data = array();
$this->load->model('setting/extension');
$extensions = $this->model_setting_extension->getExtensions('module');
foreach ($extensions as $extension) {
$modules = $this->config->get($extension['code'] . '_module');
if ($modules) {
foreach ($modules as $module) {
if ($module['layout_id'] == $layout_id && $module['position'] == 'header' && $module['status']) {
$module_data[] = array(
'code' => $extension['code'],
'setting' => $module,
'sort_order' => $module['sort_order']
);
}
}
}
}
$sort_order = array();
foreach ($module_data as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $module_data);
$this->data['modules'] = array();
foreach ($module_data as $module) {
$module = $this->getChild('module/' . $module['code'], $module['setting']);
if ($module) {
$this->data['modules'][] = $module;
}
}
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/header.tpl')) {
$this->template = $this->config->get('config_template') . '/template/common/header.tpl';
} else {
$this->template = 'default/template/common/header.tpl';
}
$this->render();
Then all done.
The only problem for this code is the slideshow cannot display as a slideshow but a static picture or pictures.
Wish you could solve it out and reply to me.
My question post:
Opencart developement: change slideshow's position
do what Huawei Chen wrote and then add these to header:
<script type="text/javascript" src="catalog/view/javascript/jquery/nivo-slider/jquery.nivo.slider.pack.js"></script>
<link rel="stylesheet" type="text/css" href="catalog/view/theme/default/stylesheet/slideshow.css" media="screen" />
and slider will be working
You can learn from controller/common/column_right.php
Check module position (line 50), you can adapt it to "header":
$module['position'] == 'column_right'
Set the output (line 69), you can adapt it to something like "header_mod" :
$this->data['modules']
You need to modificate module at admin to show additional module position.
There is no "header" module position options at admin page.
You can also use an extension that places 2 positions in header and footer. It create the same hooks, like column_left and content_top, etc.
it works with VQmod for opencart 1.5x
I think this extension will make your life super simple. http://www.opencart.com/index.php?route=extension/extension/info&token=extension_id=14467
You can add unlimited number of positions to your header, add columns and change there width all through admin
Regards
This guide helped me:
http://www.mywork.com.au/blog/create-new-module-layout-position-opencart-1-5/
I was using 1.5.6.1 Opencart version.
I read all of your answer. Forget all things.
It's very easy to call any module into header section.
Open your catalog/controller/common/header.php file
$this->data['YOUR_MODULE_NAME'] = $this->getChild('module/YOUR_MODULE_NAME');
Now Open .tpl file of header, which is located at
catalog/view/theme/YOUR_THEME/template/common/header.tpl
and echo your desire module whenever you want, like as:
<?php echo $YOUR_MODULE_NAME;?>
That's it. you are done.
You must know that your new position is a new child.
file: catalog/controller/common/header.php
$this->children = array(
'module/language',
'module/currency',
'module/cart'
);
add your new position, like this:
$this->children = array(
'common/content_new',
'module/language',
'module/currency',
'module/cart'
);
now you can echo your new position in your header.tpl