How can I include css and js file in codeigniter - php

I am trying toinclude css file in the following code.
Config :
$config['base_url'] = 'http://localhost/ASOFT/Projects/CI_search';
$config['site_url'] = 'http://localhost/ASOFT/Projects/CI_search/index.php';
$config['js'] = 'assets/js';
View:
<link rel="stylesheet" href="<?php echo $base?>/<?php echo $css?>/style.css">
<link rel="stylesheet" href="<?php echo $base?>/<?php echo $css?>/bootstrap.min.css">
<script src="<?php echo $base?>/<?php echo $js?>/jquery.min.js"></script>
<script src="<?php echo $base?>/<?php echo $js?>/jquery.js"></script>
<script src="<?php echo $base?>/<?php echo $js?>/bootstrap.min.js"></script>
I put the css file in CI_search/css and js file in CI_search/assets/js
I got the error undefined variable css and undefined variable js.Please provide solution for this problem.
UPDATE
Controller:
public function index() {
$this->data = array(
'site' => $this->config->item('site_url'),
'base' => $this->config->item('base_url'),
'css' => $this->config->item('css'),
'js' => $this->config->item('js'),
'image'=>$this->config->item('image')
);
$data = $this->data;
$data['error'] = '';
$this->load->view('index',$data);
}

As far as i can see, you din't declared $config['css'] in your config file, so it's normal to get undefined variable error for css. But you shouldn't have problem with js.
When declaring your base_url use trailing slash at the end (eg. "http://localhost/fancysite/")
Also you can use CI's url helper to use functions like base_url() or site_url() and many more. (as #Likee suggested).
config.php
// this should be the first variable in CI's config.php
$config['base_url'] = "http://localhost/ASOFT/Projects/CI_search/";
// many more lines with other configuration variables
// ..................................................
// ..................................................
// ..................................................
// your own configuration variables at the end of file
$config['css'] = 'css/';
$config['js'] = 'assets/css/';
$config['image'] = 'images/';
controller
public function index() {
// loading url helper to use base_url() function in the view,
// if you load this helper in autoload.php you don't need to load it here again
$this->load->helper('url');
// if you didn't declare data as class property
// you can simply use
// $data = array(
// 'css' => $this->config->item('css'),
// 'js' => $this->config->item('js'),
// 'image'=>$this->config->item('image')
// );
$this->data = array(
'css' => $this->config->item('css'),
'js' => $this->config->item('js'),
'image'=>$this->config->item('image')
);
// you really don't need the line below
// $data = $this->data;
$this->data['error'] = '';
$this->load->view('index',$this->data);
}
view
<link rel="stylesheet" href="<?php echo base_url($css . 'style.css'); ?>">
<link rel="stylesheet" href="<?php echo base_url($css . 'bootstrap.min.css'); ?>">
<script src="<?php echo base_url($js . 'jquery.min.js'); ?>"></script>
<!-- do you really need to include jquery.js while you included jquery.min.js above? but here we go :) -->
<script src="<?php echo base_url($js . 'jquery.js'); ?>"></script>
<script src="<?php echo base_url($js . 'bootstrap.min.js'); ?>"></script>
Probably you will need to use url helper a lot. So you can autoload it in autoload.php file in config folder. it must be somewhere around line 90
$autoload['helper'] = array('url');

There are many ways to include css and js file in codeigniter.
This how I do it.
FIRST: Create a folder outside the application folder and named it any named you liked but I prefer to named it as resources. Create a sub folders like js, css, images and others. Place all your files in here for future references.
SECOND: Open the the contants.php saved in application/config and paste this code.
define('CSS', 'http://localhost/yourfolder/resources/css');
define('JS', 'http://localhost/yourfolder/resources/js');
define('IMAGES', 'http://localhost/yourfolder/resources/images');
NOTE: Update this code depends on your needs.
THIRD: On your view file, you can access this files by,
<link rel="stylesheet" href="<?php echo(CSS.'bootstrap.min.css'); ?>">
<script type="text/javascript" src='<?php echo(CSS.'bootstrap.min.css'); ?>'></script>
Refer to this link. How can I include the CSS file in CodeIgniter?
I hope this helped.

Bind your variables to view like this:
$this->load->view('viewName', $config);
And array $config should be available in your controller method.
Instead setting $config['base_url'] you can use function base_url().

well if at all possible determine what your path structure will be and then just use it in the view with base_url() .
<link href="<?php echo base_url();?>assets/css/bootstrap.min.css" rel="stylesheet">
<script src="<?php echo base_url();?>assets/js/blahblah.js"></script>
you can even have a few simple templates, and then call the appropriate template.
if that is impossible - then push this logic and output to a model or similar so that it can be called by different controllers. otherwise you are going to have to update folder names and file paths in your controllers.

Related

How to link something from manifest.json

I'm using Webpack with the CleanWebpackPlugin, but I use an index.php. So HtmlWebpackPlugin isn't an option. I found a different plugin called WebpackManifestPlugin. This creates a file with the files and their hash called manifest.json. It looks like this:
{
"main.js": "css.d915ef.js",
"main.css": "main.d915ef.css"
}
But how do I use this in my head?
<link rel="stylesheet" type="text/css" href="dist/main.css">
Because this doesn't work.
Use that function in php script
function asset($asset_name)
{
$manifest = file_get_contents("./manifest.json");
$manifest = json_decode($manifest, true); //decode json string to php associative array
if (!isset($manifest[$asset_name])) return $asset_name; //if manifest.json doesn't contain $asset_name then return $asset_name itself
return "/dist/" . $manifest[$asset_name];
}
It will read and parse manifest.json and replace "main.js" with "css.d915ef.js"
You can use asset() function while generating yout html, like this:
<link rel="stylesheet" type="text/css" href="<?php echo asset("main.js"); ?>">
Please, be aware, that file_get_contents("./manifest.json") will only work correctly if your php script and manifest.json is in the same folder. If not - you need to provide correct path to manifest.json here.
I have a similar situation with Create React App and a PHP file.
The Create React App configuration creates an asset-manifest.json file in which all the files that are needed in the page are listed under the entrypoints key.
"entrypoints": [
"static/js/runtime-main.bff00530.js",
"static/js/2.8bab6741.chunk.js",
"static/css/main.262e5e5f.chunk.css",
"static/js/main.e2f4dbf8.chunk.js"
]
In my code I'm doing the following (expanding on #krylov123's answer):
// get the original values
$manifest = file_get_contents("./asset-manifest.json");
$manifest_values = json_decode($manifest, true);
$entrypoints = $manifest_values['entrypoints'];
Then I'm creating two separate arrays: one for the css and another for the js files. In order to do so I've created an helper function filterPaths (you may create your own):
// return only paths continaint a specific string
function filterPaths($paths, $value): array {
return array_filter($paths, function ($filename) use ($value): bool {
return strpos($filename, $value) !== false;
});
}
Here I create the two arrays:
// filter '.css' files
$css_files = filterPaths($entrypoints, '/css/');
// filter '.js' files
$js_files = filterPaths($entrypoints, '/js/');
Then in the html part I loop over the two arrays in order to print link tags for CSS and script tags for JavaScript.
This is the syntax using blade, but you can adapt it to normal php:
#foreach($css_files as $link)
<link href="{{ $link }}" rel="stylesheet">
#endforeach
#foreach($js_files as $link)
<script src="{{ $link }}"></script>
#endforeach
Another option is to disable hash inserting via webpack.config.js file.
You need to find all [hash] occurence and remove it from webpack.config.js. Then use npm run to recompile everything.
For example, you have
output: {
path: path.resolve(__dirname, './public/'),
filename: '[name].[hash].js'
}
Replace it with:
output: {
path: path.resolve(__dirname, './public/'),
filename: '[name].js'
}

PHP include header and footer with different plugins on some pages

I am building a website with php and it has 20 pages. In the homepage
I would like to have a slider and some other plugins which I include them
in the head. In the footer I link also some JS files.
When we use php we have header.php and footer.php
Some of the plugins are not needed on some pages but the header.php
and footer.php is included on those pages. Is there a way to remove
those plugins on those specific pages? or I have to include everything
even if they are not needed? Also I would like to add some other plugins
in some of the pages that are not needed in the Home Page. Should I create multiple header.php and footer.php and include them when necessary?
What is the solution to this problem?
Thanks.
Example:
Home Page those are needed:
Header.php
<link rel="stylesheet" href="plugin01.css">
<link rel="stylesheet" href="plugin02.css">
<link rel="stylesheet" href="plugin03.css">
<link rel="stylesheet" href="plugin04.css">
Footer.php
<script src="plugin01.js"></script>
<script src="plugin02.js"></script>
<script src="plugin03.js"></script>
<script src="plugin04.js"></script>
Random Page:
I need only
header.php
<link rel="stylesheet" href="plugin01.css">
<link rel="stylesheet" href="plugin02.css">
footer.php
<script src="plugin01.js"></script>
<script src="plugin02.js"></script>
What you can do is create a helper function to assist with loading required assets and then have a common header.php / footer.php like this:
helpers.php
<?php
function loadStyles($assets = array()) {
foreach ($assets as $asset) {
echo '<link rel="stylesheet" href="'. $asset .'.css">'."\r\n";
}
}
function loadScripts($assets = array()) {
foreach ($assets as $asset) {
echo '<script src="'. $asset .'.js"></script>'."\r\n";
}
}
?>
Then, update your header.php like this:
<?php
// Load required stylehseets for this page
if (isset($styleAssets)) {
loadStyles($styleAssets);
}
// Rest of your common header stuff here
?>
Then do something similar with footer.php like this:
<?php
// Load required scripts for this page
if (isset($scriptAssets)) {
loadScripts($scriptAssets);
}
// Rest of your common footer stuff here
?>
Then you put it all together like this. For example, this is your "home.php" page:
<?php
// Load helpers
require 'helpers.php'
// Define required styles for this page
$styleAssets = array(
'plugin01',
'plugin02',
'plugin03',
'plugin04'
);
// Load header
require 'header.php'
// Rest of the "home" page code goes here
// Define required scripts for this page
$scriptAssets = array(
'plugin01',
'plugin02',
'plugin03',
'plugin04'
);
// Load footer
require 'footer.php'
?>
Now, for another random.php page, you simply re-use the script like this:
<?php
// Load helpers
require 'helpers.php'
// Define required styles for this page
$styleAssets = array(
'plugin01',
'plugin02'
);
// Load header
require 'header.php'
// Rest of the "random" page code goes here
// Define required scripts for this page
$scriptAssets = array(
'plugin01',
'plugin02'
);
// Load footer
require 'footer.php'
?>
You'll have to define for each page its required plugins (resources).
In the header and footer files, simply loop through that array and call the resources.
It's a bit more work but it's a better organised method and in case you'll have in the future a new page with other plugins, instead of writing patched, you'll easily update it using this mechanism.
PageX.php
//$this_page = 'pageX';
$plugins = array(
'css' => array(
'pluginName1' => 'plugin-name-1.css',
'pluginName2' => 'plugin-name-2.css',
),
'js' => array(
'pluginName1' => 'plugin-name-1.js'
)
);
require_once 'header.php;
//....
//...
require_once 'footer.php';
Header.php
foreach($plugins['css'] as $name => $resource_url){
echo '<link rel="stylesheet" href="'.$resource_url.'">';
}
Footer.php
foreach($plugins['js'] as $name => $resource_url){
echo '<script src="'.$resource_url.'"></script>';
}
In your Header.php you can check for the current page.
if( basename($_SERVER['PHP_SELF']) == 'homepage.php')
{ ?>
<link rel="stylesheet" href="plugin01.css">
<link rel="stylesheet" href="plugin02.css">
<link rel="stylesheet" href="plugin03.css">
<link rel="stylesheet" href="plugin04.css">
<?php
}

CodeInteger Error Message: Message: Call to undefined function link_tag(

<title>Login</title>
<!-- CSS -->
<?php echo link_tag('assets/css/bootstrap.min.css')?>
<?php echo link_tag('assets/font-awesome/css/font-awesome.min.css')?>
<?php echo link_tag('assets/css/form-elements.css')?>
<?php echo link_tag('assets/ico/favicon.png')?>
<?php echo link_tag('assets/ico/apple-touch-icon-144-precomposed.png')?>
<?php echo link_tag('assets/ico//apple-touch-icon-114-precomposed.png')?>
<?php echo link_tag('assets/ico//apple-touch-icon-72-precomposed.png')?>
<?php echo link_tag('assets/ico//apple-touch-icon-57-precomposed.png')?>
</head>
i did not write any Controller or Model class , just to include the above Styles and Images in page , it show the Message: "Message: Call to undefined function link_tag()"Error even i have wrote the following code also in config/autoload file $autoload['helper'] = array('url');"" Error e
link_tag() is a function which defined in HTML helper. You should load HTML helper first.
You have 2 options, first one:
Open, application/config/autoload.php and add 'html' value in helper array.
Second one:
Add this line top of your code.
$this->load->helper('html');
Then, edit your lines like this:
$link = array
(
'href' => 'assets/css/bootstrap.min.css',
'rel' => 'stylesheet',
'type' => 'text/css',
);
echo link_tag($link);
But I think you can just use site_url() function. If you want to use site_url(), you should load url helper and edit your lines like below:
<link href="<?php echo site_url('assets/css/bootstrap.min.css'); ?>" rel="stylesheet" type="text/css" />
You using wrong helper. You should add to your autoload 'html'
Please check documentation
https://ellislab.com/codeigniter/user-guide/helpers/html_helper.html#link_tag
Try using base_url(); instead.
<?php echo base_url('assets/css/bootstrap.min.css')?>

APPLICATION PATH in Zend Framework getting appended to virtual host name

In my Layout, when I do this
<?php $js = APPLICATION_PATH."/../public/js"; ?>
<script src = <?php echo $js."/signup_layout_js.js"; ?> ></script>
I get a js error
http://proj_name/home/aman/Work/proj_name/public/js/signup_layout_js.js
My APPLICTION_PATH is getting appended to http://proj_name/, I dont want that.
But if I do this, it works fine on http://proj_name/ but breaks when i go to a controller/action like http://proj_name/Controller/Action
<script src ="./js/signup_layout_js.js"></script>
How can I correct this. Thanks.
Also in my index.php, APPLICATION_PATH is
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
Thanks..
Link scripts like this:
<script src = "<?= $this->baseUrl() . '/js/signup_layout_js.js' ?>" ></script>
Or use headScript helper:
//put this in header
<?= $this->headScript(); ?>
//put this before closing body tag
<?= $this->inlineScript() ?>
//and this anywhere in you code ($this is view object)
$this->headScript()
->prependFile($this->baseUrl() . '/js/jquery-1.7.2.min.js')
->appendFile($this->baseUrl() . '/js/flying-header.js')
->appendScript('
var google_conversion_id = 9999999;
var google_custom_params = window.google_tag_params;
var google_remarketing_only = true;');
Your entire path is part of the src for your scripts because you are prepending it. Try echoing the value of your APPLICATION_PATH constant. This is not the correct behaviour for referencing static files in web applications.
In your case, you should look into using Zend Framework's built-in headScript and inlineScript view helpers for this. You shouldn't need to write the script DOM tags yourself.

how and where to include js and css for modules?

I have modules for category:
+modules/
+category/
+assets/
+css/
+js/
+images/
+components/
+controllers/
+models/
+views/
-CategoryModule.php
What is the best way to includes the css and jss to all views?
Publish and register in CategoryModule init method - this will make available your css and js in category module.
Something like this:
public function init() {
$path = $this->assetManager->publish(Yii::getPathOfAlias('application.modules.category.assets'));
$this->clientScript->registerCssFile($path . '/css/some-css.css', 'screen, projection');
$this->clientScript->registerScriptFile($path . '/js/some-js.js');
}
create module layout file under views/layout and call it in module config file as
$this->layoutPath = Yii::getPathOfAlias('application.modules.moduleName.views.layouts');
$this->layout = '/layouts/layoutname';
register all the js and css file as #PeterM mentioned
Create a folder "layouts" in your views folder. Create main.php in that layouts folder.
In your , add following code:
<link rel="stylesheet" href="<?php echo Yii::app()->request->baseUrl; ?>/css/style.css" type="text/css" media="screen"/>
<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/cycle.js"></script>
This is your default layout. So add,
<?php echo $content; ?>
This is another method to include css and js in all views.
Easy using this static method
<?php Yii::app()->clientScript->registerCssFile(Yii::getPathOfAlias('application.modules.curriculo.assets') . '/bootstrap/datepicker/css/datepicker.css'); ?>
<?php Yii::app()->clientScript->registerScriptFile(Yii::getPathOfAlias('application.modules.curriculo.assets') . '/bootstrap/datepicker/js/bootstrap-datepicker.js'); ?>
This should help you:
http://www.yiiframework.com/wiki/249/understanding-the-view-rendering-flow/
All three sections (beginContent, container and endContent) are explained in detail.

Categories