How to include css and js files (Codeigniter + Twig) - codeigniter

im new in the forum and im spanish... sorry for my low level of english...
Im using Codeigniter with twig engine in my project but I having some problems...
When I use:
<link rel="stylesheet" href="{{ asset('assets/css/bootstrap.min.css') }}">
Codeigniter throws an exception. It says:
The function "asset" does not exist. Did you mean "assert" in "index.html.twig" at line 12 --- #0 /volume1/web/ci/application/libraries/Twig/ExpressionParser.php(351): Twig_ExpressionParser->getFunctionNodeClass('asset', 12) #1 /volume1/web/ci/application/libraries/Twig/ExpressionParser.php(144): Twig_ExpressionParser->getFunctionNode('asset', 12) #2 /volume1/web/ci/application/libraries/Twig/ExpressionParser.php(84): Twig_ExpressionParser->parsePrimaryExpression() #3 /volume1/web/ci/application/libraries/Twig/ExpressionParser.php(41): Twig_ExpressionParser->getPrimary() #4 /volume1/web/ci/application/libraries/Twig/Parser.php(141): Twig_ExpressionParser->parseExpression() #5 /volume1/web/ci/application/libraries/Twig/TokenParser/Block.php(45): Twig_Parser->subparse(Array, true) #6 /volume1/web/ci/application/libraries/Twig/Parser.php(187): Twig_TokenParser_Block->parse(Object(Twig_Token)) #7 /volume1/web/ci/application/libraries/Twig/Parser.php(95): Twig_Parser->subparse(NULL, false) #8 /volume1/web/ci/application/libraries/Twig/Environment.php(543): Twig_Parser->parse(Object(Twig_TokenStream)) #9 /volume1/web/ci/application/libraries/Twig/Environment.php(595): Twig_Environment->parse(Object(Twig_TokenStream)) #10 /volume1/web/ci/application/libraries/Twig/Environment.php(335): Twig_Environment->compileSource('...', 'index.html.twig') #11 /volume1/web/ci/application/libraries/Twig.php(90): Twig_Environment->loadTemplate('index.html.twig') #12 /volume1/web/ci/application/controllers/welcome.php(15): Twig->display('index.html.twig', Array) #13 [internal function]: Welcome->index() #14 /volume1/web/ci/system/core/CodeIgniter.php(360): call_user_func_array(Array, Array) #15 /volume1/web/ci/index.php(202): require_once('/volume1/web/ci...') #16 {main}
Also throws an exception for any function twig
What is the problem?
Thank you!
Edit
Ok guys, I haven't been unable to resolve my problem, the function doesn't exists but I have got to include my css and js files and also using twig together. The problem was on my .htaccess file (the file is on root directory in my server). The file had written:
RewriteEngine on
RewriteCond $1 !^(index.php|css|js|images|robots.txt)
RewriteRule ^(.*)$ /ci/index.php/$1 [L]
So I created another .htaccess file on "/ci/assets/.htaccess" with this code:
RewriteEngine off
RewriteCond $1 !^(index.php|css|js|images|robots.txt)
RewriteRule ^(.*)$ /ci/index.php/$1 [L]
I don't know if this is the best way but this is valid for me and I can work fine.
Any sugestion?

You need helper file that contents asset() function.
But maybe you have a typo:
<link rel="stylesheet" href="{{ assert('assets/css/bootstrap.min.css') }}">

asset() takes part of the Symfony2 project, not the Twig one.
You should create this function in codeigniter by yourself first.
1) In your custom Twig library, add the following line:
$this->_twig_env->addFunction(
new Twig_SimpleFunction('asset', 'asset',
array('is_safe' => array('html')))
);
2) In your helpers, add the following function (replace assets/ by the path to your assets, here I assume your images, js, ... are available in assets/images, assets/js, assets/...).
if (!function_exists('asset'))
{
function asset()
{
return base_url() . 'assets/';
}
}

You Might want to add a filter like eg usage is as below
Link rel="stylesheet" href="{{ 'assets/css/bootstrap.min.css' | asset }}">
to achieve above you might want to extend twig filters class and add your filter.
requrie_once("path of Twig_Extension class); // update this
use Twig_Extension;
use Twig_Filter_Method;
class customExtension extends Twig_Extension
{
/**
* Returns the name of the extension.
*
* #return string The extension name
*/
function getName()
{
return "customExtension";
}
public function getFilters()
{
return array(
'asset' => new Twig_Filter_Method($this,'twig_asset_filter'),
);
}
/**
* #param $path
*
* #return string
*/
function twig_asset_filter($path)
{
return 'assets/'.$path;
}
after which you can use it in same way - this extension is already written and is accessible via composer..
check this link https://github.com/iddigitalagency/Codeigniter-twig-twigextensions

Related

Trying to visit /js/app.js net::ERR_ABORTED 500 (Internal Server Error)

My problem isn't easy to describe, i guess I forgot something obvious but I just can't figure out what..
Here is the error: GET http://127.0.0.1/ideayear/850/js/app.js net::ERR_ABORTED 500 (Internal Server Error)
And here is the problem:
Until now I had
in web.php
Route::get('idea/{n}', 'IdeaController#idea')->name('idea');
And I want to add the year
Route::get('ideayear/{n}/{m}', 'IdeaController#idea')->name('idea');
public function idea($idea, $year){
$idea = substr($idea, 0, strpos($idea, "-"));
$sql = " SELECT BLABLA where year like ..."
$array = DB::connection('ideas')->select( DB::connection('ideas')->raw($sql));
return view('ideas/idea', ['idea' => json_encode($array), 'defyear' => $year] );
}
when I had public function idea($idea){} it worked well, but since I added $year, I get this strange issue when visiting http://127.0.0.1/ideayear/850/2018
Give me the error:
GET http://127.0.0.1/ideayear/850/js/app.js net::ERR_ABORTED 500 (Internal Server Error)
And I have absolutely no idea why it's for some reason trying to visit js/app.js
Here is idea.blade.php (in case if it helps)
#extends('template')
#section('contenu')
<div>
<div id="app">
<ideapage ideas="{{ $idea }}" defyear="{{ $defyear }}"></ideapage>
</div>
</div>
#endsection
[EDIT] Content of
(I removed almost everything from IdeaPage.vue, same problem)
<template>
<div> {{ideas}}
{{defyear}}
</div>
</template>
<script>
export default {
props: {
ideas: String,
defyear: String
}
}
</script>
Here is the error in laravel.log
#0 C:\\laragon\\www\\projet\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php(624): Illuminate\\Database\\Connection->runQueryCallback(Object(Illuminate\\Database\\Query\\Expression), Array, Object(Closure))
#1 C:\\laragon\\www\\projet\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php(333): Illuminate\\Database\\Connection->run(Object(Illuminate\\Database\\Query\\Expression), Array, Object(Closure))
#2 C:\\laragon\\www\\projet\\app\\Http\\Controllers\\IdeaController.php(121): Illuminate\\Database\\Connection->select(Object(Illuminate\\Database\\Query\\Expression))
#3 [internal function]: App\\Http\\Controllers\\IdeaController->idea('850', '', 'app.js')
#4 C:\\laragon\\www\\projet\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Controller.php(54): call_user_func_array(Array, Array)
#5 C:\\laragon\\www\\projet\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\ControllerDispatcher.php(45): Illuminate\\Routing\\Controller->callAction('idea', Array)
Why is it trying to visit idea('850', '', 'app.js')** ? i really don't get this...

Laravel index route issue when using for a subsection in another fw (external public dir)

I'm using a Laravel app with an external public directory, e.g. root/Laravel, and root/html/public.
I need this app to load from a require on a php file (root/html/this-section.php) that already has another framework loading it, hence that other fw has its own head, and body tag. This app will load between the header and footer of that file.
When I set up the routes, i notice that both of the following routes work, but i get different results.
Route::get('/', 'HomeController#index');
Route::get('/this-section', 'HomeController#index');
# this also works as a substitute for above, still same issue though
Route::get('//', 'HomeController#index');
These are the same pages, the controller has the same code, I would expect that the pages load the same. Whats happening is the main index site.com/ is loading correctly, but the latter is loading without the html <head> and <body> tags which exist on this-section.php. So essentially, the latter is not loading the parent page, its only loading what it sees on the blade templates.
I suspect maybe either need to add a rewrite to the .htaccess to cover this, or set up a custom redirect or return of a view or response in the controller (I need help here with suggestions) where I can then make a second method, e.g. thisSectionIndex() and return that suggestion.
At first I had things working with overriding the public_path() to the correct path this-section however that backfired when i made the sub routes
e.g. when using the following route setup
Route::get('/', 'HomeController#index');
Route::get('/feature', 'SectionController#feature');
It caused the feature route to be 500 or 404, I think it couldn't find the files, so I realized I needed to unfortunately add in the /this-section portion to the route ,which opened a can of worms pretty much.
Route::get('/', 'HomeController#index');
Route::get('/this-section', 'HomeController#index');
Route::get('/this-section/feature', 'SectionController#feature');
ON a side note, some fallout for this which I found a temporary work-around for already, was {{assets()}} broke. I had assets() overridden to not have to use the this-section/ portion, e.g. like this {{assets(/this-section/css/styles.css)}}. The temp worksround was to unfortunately have to manually add the paths and forego using {{assets()}} altogether in the blade templates until i figure that part out, because no path is working for them now.
Some background info:
Im overriding the public path like this
#Laravel\app\SectionApplication
class SectionApplication extends \Illuminate\Foundation\Application
{
public function publicPath()
{
$newBasePath = $this->basePath . DIRECTORY_SEPARATOR . '..' .
DIRECTORY_SEPARATOR . 'html/this-section';
return $newBasePath;
}
}
#Laravel/bootstrap/app.php
// $app = new Illuminate\Foundation\Application(
// realpath(__DIR__.'/../')
// );
$app = new App\SectionApplication(
realpath(__DIR__.'/../')
);
Here is the pertinent(adjusted) parts of the laravel bootstrapper index (html/this-section/index.php)
function public_path($path = '')
{
return realpath(__DIR__);
}
//adjust your relative laravel framework path here
$laravelRelPath = '../../Laravel';
//override the blade {{asset()}} helper
function asset($path, $secure = null)
{
$newPubPath = 'this-section/'; //relative from html where the index.php will be
return app('url')->asset($newPubPath . $path, $secure);
}
.htaccess is located outside of Laravel, and in html/
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
#Rewritebase /this-section/
#RewriteRule ^(.*)$ this-section/$1 [L]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
With the help of this topic
and this topic I found a working solution. Adjustments are needed When your loading in the application. You want to bootstrap it from the same path as the file loads the bootstrap, then override the .htaccess for that particular path only.
move laravels bootstrap file html/this-section/index.php file up one directory, next to the file html/this-section.php, and rename it to html/this-section-laravel-boostrap.php
adjust the path for laravel on html/this-section-laravel-boostrap.php by removing one directory ../
e.g. from $laravelRelPath = '../../Laravel'; to $laravelRelPath = '../Laravel';
add the following code to htlm/this-section.php (the file loads the bootstrap)
if (strpos($_SERVER['REQUEST_URI'],'this-section') !== false) {
require_once('this-section-laravel-bootstrap.php');
}
add the following to the .htaccess to snag the uri
#Rewritebase /
RewriteRule ^this-section/?$ / [L,NC]
The only route needed for this-section
Route::get('/this-section', 'HomeController#index')
In your blade templates, call your assets like this so they load on every sub sections url, e.g. for css
<link rel="stylesheet" href="/this-section/css/styles.css">
The application will now bootstrap, and always use the outer contents from the parent file that loads it. See below for an example parent test file(html/this-section.php) for this.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Parent Application</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body>
<header>
<nav>
<ul>
<li>menu</li>
</ul>
</nav>
</header>
<?php
<--! laravel sandwich -->
if (strpos($_SERVER['REQUEST_URI'],'this-section') !== false) {
require_once('this-section-laravel-bootstrap.php');
}
?>
<footer>
<p>Copyright <?php echo date('Y'); ?> - All rights reserved.</p>
</footer> -->
</body>
</html>
Bonus
assets are now loading correctly, you probably dont need step 5.
{{asset('css/vendors.css')}}

Magento Nofrills Layouts progmatically not working Magento 1.8.1

I am trying to get to grips with working with layouts and came across Alan Storm's book Nofrills Magento Layouts (Good Book).
I have gone through the examples right up to page 19 adding in a new class under the Advanced Block Functionality section.
I have created all the files and templates as per the examples but I am now getting an error and cannot seem to progress until it is fixed.
The block class looks like this:
<?php
class Nofrills_Booklayout_Block_Helloworld extends Mage_Core_Block_Template
{
public function _construct()
{
$this->setTemplate('helloworld.phtml');
return parent::_construct();
}
}
?>
The IndexController class looks like this:
<?php
class Nofrills_Booklayout_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$block_1 = new Mage_Core_Block_Text();
$block_1->setText('Original Text');
$block_2 = new Mage_Core_Block_Text();
$block_2->setText('The second sentence');
$main_block = new Nofrills_Booklayout_Block_Helloworld();
//$main_block->setTemplate('../helloworld.phtml');
$main_block->setChild('the-first',$block_1);
$main_block->setChild('the-second', $block_2);
//$block_1->setText('Wait, I want this text instead!');
echo $main_block->toHtml();
}
public function helloblockAction()
{
$block_1 = new Mage_Core_Block_Text();
$block_1->setText('Original Text');
$block_2 = new Mage_Core_Block_Text();
$block_2->setText('The second sentence');
$main_block = new Nofrills_Booklayout_Block_Helloworld();
//$main_block->setTemplate('helloworld.phtml');
$main_block->setChild('the-first',$block_1);
$main_block->setChild('the-second', $block_2);
echo $main_block->toHtml();
}
}
and the template looks like this:
<h1>hello world</h1>
<p>
<?php echo $this->getChildHtml('the-first'); ?>
</p><p>
<?php echo $this->getChildHtml('the-second'); ?>
</p>
However when i goto my url to call the page:
http://www.phmagento.com/nofrills_booklayout/index/index
http://www.phmagento.com/nofrills_booklayout/index/helloblock
I get this error which is totally confusing me:
Warning: include(C:\xampp\htdocs\phmagento\includes\src\Nofrills_Booklayout_Block_Helloworld.php): failed to open stream: No such file or directory in C:\xampp\htdocs\phmagento\includes\src\Varien_Autoload.php on line 93
#0 C:\xampp\htdocs\phmagento\includes\src\Varien_Autoload.php(93): mageCoreErrorHandler(2, 'include(C:\xamp...', 'C:\xampp\htdocs...', 93, Array)
#1 C:\xampp\htdocs\phmagento\includes\src\Varien_Autoload.php(93): Varien_Autoload::autoload()
#2 [internal function]: Varien_Autoload->autoload('Nofrills_Bookla...')
#3 C:\xampp\htdocs\phmagento\app\code\local\Nofrills\Booklayout\controllers\IndexController.php(12): spl_autoload_call('Nofrills_Bookla...')
#4 C:\xampp\htdocs\phmagento\includes\src\__default.php(13969): Nofrills_Booklayout_IndexController->indexAction()
#5 C:\xampp\htdocs\phmagento\includes\src\__default.php(18331): Mage_Core_Controller_Varien_Action->dispatch('index')
#6 C:\xampp\htdocs\phmagento\includes\src\__default.php(17865): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#7 C:\xampp\htdocs\phmagento\includes\src\__default.php(20465): Mage_Core_Controller_Varien_Front->dispatch()
#8 C:\xampp\htdocs\phmagento\app\Mage.php(684): Mage_Core_Model_App->run(Array)
#9 C:\xampp\htdocs\phmagento\index.php(87): Mage::run('', 'store')
#10 {main}
If anybody has any clues as to why I am getting this error or what I am doing wrong it would be greatly appreciated.
Many thanks
Graham
The autoloader is trying to load the Nofrills_Booklayout_Block_Helloworld class from C:\xampp\htdocs\phmagento\includes\src\Nofrills_Booklayout_Block_Helloworld.php. Are you sure that file exists? It should contain the block from your first code snippet.

Admin url is not working properly in codeigniter

I have created a small application in codeigniter. Frontend is running properly where as admin section is not opening.
I'm trying to open as yourdomain/admin/index.php/user/(But it showing 404 not found error).
So how to view the catalog section of admin?
Here is my file structure and file content for admin
D:\wamp\www\CodeIgniter\application\views\admin\catalog\catalog_view.php
<?php if (!defined('BASEPATH')) exit(__('No direct script access allowed')); ?>
<?php $this->load->view('admin/inc/header'); ?>
<h1><?php echo __('Catalog Manager'); ?></h1>
<p>Coming Soon...</p>
<?php $this->load->view('admin/inc/footer'); ?>
D:\wamp\www\CodeIgniter\application\controllers\admin\catalog\catalog.php
<?php
/**
* Admin User Controller
*/
class User extends MY_Controller
{
public function __construct()
{
parent::MY_Controller();
}
function index()
{
$data = '';
//---
$html_string = $this->load->view('admin/catalog/catalog_view', $data, true); //Get view data in place of sending to browser.
Library('process')->view($html_string);
}
}
Do you have a good htaccess setup?
Without htaccess you can access admin->index(); this with index.php/admin/index/
Your admin controller file isn't in the right order:
/application/controllers/admin/catalog/catalog.php
Without routing (http://ellislab.com/codeigniter/user-guide/general/routing.html) you cannot make this work, and you need to change your class name from user to catalog.
Ideally, you move the controller to /controllers/admin.php.
Then you can do index.php/admin and the index function will show. No routing needed what so ever.
you can't access it in that way yourdomain/admin/index.php/user/ you have to try first site.com/index.php/admin/...
but you have to be sure you created a controller named controller/admin.php which loads your views/admin/ pages
cause if you don't want to touch the CI core or extend it the rule is
:
http://www.site.com/index.php/controller/method/params
so in your case i would do:
class Admin exntends CI_Controller{
function index(){
//admin home page
//www.site.com/index.php/admin
}
function users(){
//admin users page
//www.site.com/index.php/admin/users
}
//... and so on
}
No Routes needed and if you want to remove index.php from your url just place this htaccess in your project root:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
Please use the route file few settings and easily set the admin URL.
$route['admin'] = 'admin/dashboard';

File /View/Elements/lookup.ctp won't render inside /View/Layouts/default.ctp (error displayed)? How can I do it?

I want to embed an HTML input form (search bar) in /View/Layouts/default.ctp (which is Homepage presentation layout of the site). I've created /View/Elements/lookup.ctp with the following code (I wrote Element because I wanted to include that search bar on every page of the site):
<?php
echo $this->Form->create('Search', array('action' => 'lookup', 'accept-charset' => 'utf-8'));
echo $this->Form->input(array('type' => 'search', 'name' => 'search', 'placeholder' => 'enter search term'));
echo $this->Form->button('Search', array('type' => 'button', 'value' => 'submit'));
echo $this->Form->end();
?>
The search bar itself should look like this:
___________________________ ______________
| enter search term | | Search | <--- button
|_________________________| |______________|
↑
search bar
The generated code in /View/Layouts/default.ctp must be like this:
<form id="searchForm" method="post" action="/searches/lookup" accept-charset="utf-8">
<input type="search" name="search" placeholder="enter search term" />
<button type="button" name="submit" value="submit">Search</button>
</form>
I included line:
<?php echo $this->element('lookup'); ?>
in /View/Layouts/default.ctp (which embeds the Element), but when I go to Homepage, it won't render this element and the error appears:
( #Wylie: Yes, you're right. It wasn't the whole error. Here's the complete error )
#0 C:\wamp\www\lib\Cake\Model\Datasource\DboSource.php(436): PDOStatement->execute(Array)
#1 C:\wamp\www\lib\Cake\Model\Datasource\Database\Mysql.php(307): DboSource->_execute('SHOW FULL COLUM...')
#2 C:\wamp\www\lib\Cake\Model\Model.php(1226): Mysql->describe(Object(Search))
#3 C:\wamp\www\lib\Cake\View\Helper\FormHelper.php(197): Model->schema()
#4 C:\wamp\www\lib\Cake\View\Helper\FormHelper.php(450): FormHelper->_introspectModel('Search', 'fields')
#5 C:\wamp\www\azil\View\Elements\lookup.ctp(2): FormHelper->create('Search', Array)
#6 C:\wamp\www\lib\Cake\View\View.php(595): include('C:\wamp\www\azi...')
#7 C:\wamp\www\lib\Cake\View\View.php(317): View->_render('C:\wamp\www\azi...', Array)
#8 C:\wamp\www\azil\View\Layouts\default.ctp(91): View->element('lookup')
#9 C:\wamp\www\lib\Cake\View\View.php(595): include('C:\wamp\www\azi...')
#10 C:\wamp\www\lib\Cake\View\View.php(411): View->_render('C:\wamp\www\azi...')
#11 C:\wamp\www\lib\Cake\View\View.php(373): View->renderLayout('<h2>Database ta...', 'default')
#12 C:\wamp\www\lib\Cake\Controller\Controller.php(900): View->render('error500', NULL)
#13 C:\wamp\www\lib\Cake\Error\ExceptionRenderer.php(282): Controller->render('error500')
#14 C:\wamp\www\lib\Cake\Error\ExceptionRenderer.php(191): ExceptionRenderer->_outputMessageSafe('error500')
#15 [internal function]: ExceptionRenderer->_cakeError(Object(MissingTableException))
#16 C:\wamp\www\lib\Cake\Error\ExceptionRenderer.php(165): call_user_func_array(Array, Array)
#17 C:\wamp\www\lib\Cake\Error\ErrorHandler.php(127): ExceptionRenderer->render()
#18 [internal function]: ErrorHandler::handleException(Object(MissingTableException))
#19 {main} [<b>CORE\Cake\Error\ErrorHandler.php
Missing table?! What missing table, it just need to add a couple of HTML lines inside a /View/Layouts/default.ctp. I don't understand what's going on. Please help. Thank you.
Cake expects a Model to have a corresponding database table. Based on the incomplete error output Cake looks for a searches table in the database, but can't find it. Because you include an element which contains a form belonging to the Search Model Cake queries the database for a description of the columns to correctly display the form.
Are you certain you want to have a separate Controller and Model for searching? search could also be an action of the relevant Controller (the PostsController, for example).
Of course, if you need a global Search model which can query several models (Posts, Pages, Users, for example) modelising might make sense. You can tell Cake that a Model doesn't have a database table:
public $useTable = false;

Resources