It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What CodeIgniter library can provide this funcionality??
http://media.railscasts.com/videos/008_content_for.mov
It seems so simple on rails but I just cant find a simple way to achieve this on codeigniter.. please help.. I hate having to insert my styles or javascript in the body of the document
I hate templates like Smarty or http://williamsconcepts.com/ci/codeigniter/libraries/template/
Using my own implementation of Zend-like layout.
Add hook /application/hooks/Layout.php:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
/**
*
*/
class Layout {
function render() {
global $OUT;
$CI = & get_instance();
$output = $CI->output->get_output();
if (!isset($CI->layout)) {
$CI->layout = "default";
}
if ($CI->layout != false) {
if (!preg_match('/(.+).php$/', $CI->layout)) {
$CI->layout .= '.php';
}
$requested = BASEPATH . '../application/layouts/' . $CI->layout;
$default = BASEPATH . '../application/layouts/default.php';
if (file_exists($requested)) {
$layout = $CI->load->file($requested, true);
} else {
$layout = $CI->load->file($default, true);
}
$view = str_replace("{content}", $output, $layout);
$view = str_replace("{title}", $CI->title, $view);
$scripts = "";
$styles = "";
$metas = "";
if (count($CI->meta) > 0) { // Массив с мета-тегами
$metas = implode("\n", $CI->meta);
}
if (count($CI->scripts) > 0) { // Массив со скриптами
foreach ($CI->scripts as $script) {
$scripts .= "<script type='text/javascript' src='" . base_url() . "js/" . $script . ".js'></script>";
}
}
if (count($CI->styles) > 0) { // Массив со стилями
foreach ($CI->styles as $style) {
$styles .= "<link rel='stylesheet' type='text/css' href='" . base_url() . "css/" . $style . ".css' />";
}
}
if (count($CI->parts) > 0) { // Массив с частями страницы
foreach ($CI->parts as $name => $part) {
$view = str_replace("{" . $name . "}", $part, $view);
}
}
$view = str_replace("{metas}", $metas, $view);
$view = str_replace("{scripts}", $scripts, $view);
$view = str_replace("{styles}", $styles, $view);
$view = preg_replace("/{.*?}/ims", "", $view); // Подчищаем пустые неподгруженные части шаблона
} else {
$view = $output;
}
$OUT->_display($view);
}
}
?>
Then enable hooks in your /application/config/config.php:
$config['enable_hooks'] = TRUE;
After that add to /application/config/hooks.php:
$hook['display_override'][] = array('class' => 'Layout',
'function' => 'render',
'filename' => 'Layout.php',
'filepath' => 'hooks'
);
Create folder /application/layouts/
Create file /application/layouts/default.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>{title}</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
{metas}
{scripts}
{styles}
<link rel="icon" href="<?= base_url() ?>favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="<?= base_url() ?>favicon.ico" type="image/x-icon" />
</head>
<body>
<div class="head">
{head}
</div>
<div class="content">
{content}
</div>
</body>
</html>
Use it from controller:
class main extends MY_Controller {
function __construct() {
parent::Controller();
$this->parts[head] = $this->load->view("frontend/global/header.php", null, true);
$this->scripts = array("JQuery/jquery-1.4.2.min", "JQuery/form", "Core", "Frontend");
$this->styles = array("style");
$this->title = "Blah blah";
}
function index() {
$this->load->view('frontend/index.php');
}
}
I've achieved this in the past using this Template Library. From the documentation:
The Template library, written for the
CodeIgniter PHP-framework, is a
wrapper for CI’s View implementation.
Template is a reaction to the numerous
questions from the CI community
regarding how one would display
multiple views for one controller, and
how to embed “views within views” in a
standardized fashion. In addition,
Template provides extra Views loading
capabilities, the ability to utilize
any template parser (like Smarty), and
shortcuts for including CSS,
JavaScript, and other common elements
in your final rendered HTML.
Specifically, check out the library's additional utilities. It allows you to put something like this in your controller:
$this->template->add_js('js/YourJavascriptFile.js');
or
$this->template->add_js('alert("Hello!");', 'embed');
Echo $_scripts in your template
(preferably in the <head> section) to
utilize JavaScript added via this
method.
Similarly, you can do the same with your CSS:
$this->template->add_css('css/main.css');
$this->template->add_css('#logo {display: block}', 'embed', 'print');
..and simply echo $_styles in your <head> section.
Hope that helps.
Check out Twig - it supports "inheritance" (instead of the traditional include header, include footer, etc)
http://www.twig-project.org/
CodeIgniter helper:
http://github.com/jamiepittock/codeigniter-twig
or
http://github.com/MaherSaif/codeigniter-twig
(haven't tried either, but looks like the latter is a fork w/the latest commits)
I had the same problem with finding a advance layout library as well,
so i wrote my own version which also fits your need (using YAML file).
Features
Manage layouts, page title, metas, css and js with YAML file for cleaner and lighter controllers.
Default configs can be overwritten in controller configs. So that you can split your css and js into smaller files for more flexible design.
Combine and minify css and js files in production mode for faster page loading.
Usage
// in the controller
$this->view->render();
This lib will get the layout, view, page title, css, js, metas from your YAML configs
Documentation
Please see this post for more detail
download
Download source code from Github
Related
In many examples and documents I generally see that the page title is set via someController->main.blade.php->somePage.blade.php. Something like:
SomeController.php
public function someAction()
{
$title = 'Some Title';
return view('somePage', ['title'=>$title]);
}
main.blade.php
<head>
<title> #section('title') | Page #show </title>
...
somePage.blade.php
#section ('title')
{{$title}} #parent
#endsection
Wouldn't it be mode convenient to set it directly/only over the controller and blade layout file? I mean something like:
SomeController.php
public function someAction()
{
$title = 'Some Title';
return view('somePage', ['title'=>$title]);
}
main.blade.php
<head>
<title>{{ $title }}</title>
...
Wouldn't it be better to use it in that way?
I prefer not to assign the title from the controller - it's content and should be in the template from my point of view. I like to have a section in the template like
//layout file
<title> FancyApp - #yield('title')</title>
// Template
#section('title', 'Page Title')
I am trying to make a simple example with highlight.js but I can not make it work. I am not familiar with highlight.js. Here is my code and I dont know what`s wrong in it. Any idea! Thanks in advance.
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/styles/default.min.css">
<script src="https://code.jquery.com/jquery-2.2.2.min.js" integrity="sha256-36cp2Co+/62rEAAYHLmRCPIych47CvdM+uTBJwSzWjI=" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/highlight.min.js"></script>
<script type='text/javascript'>
hljs.initHighlightingOnLoad();
$(document).ready(function() {
$('#myBlock').each(function(i, e) {hljs.highlightBlock(e)});
});
</script>
</head>
<body>
<div id="myBlock">
<pre><code class="php">
require_once 'Zend/Uri/Http.php';
abstract class URI extends BaseURI
{
/**
* Returns a URI
*
* #return URI
*/
static public function _factory($stats = array(), $uri = 'http')
{
$uri = explode(':', $uri, 2);
$schemeSpecific = isset($uri[1]) ? $uri[1] : '';
$desc = 'Multi
line description';
// Security check
if (!ctype_alnum($scheme)) {
throw new Zend_Uri_Exception('Illegal scheme');
}
return [
'uri' => $uri,
'value' => null,
];
}
}
</code></pre>
</div>
</body>
</html>
You need to change the way you read the css and javascript files a bit:
The css file:
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/styles/default.min.css">
The javascript file:
<script src="http://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.2.0/highlight.min.js"></script>
Yes, I know, you used the way it was on the original site, but it seems they made a mistake, when they wrote the example codes.
I read this officail Joomla article about Microdata: http://docs.joomla.org/Microdata
I tried put this meta element in the head section of my Joomla website:
<meta itemprop="name" content="title of your content">
By this code:
$scope="itemprop";
$property="name";
$content="title";
JMicrodata::htmlMeta($content, $property, $scope = '', $inverse = false);
But no success! Can somebody tell me whats the wrong?
Solutions
To add this meta tag in you <head> section of a Joomla website:
<meta itemprop="name" content="title of your content">
You can use one of the following solutions
1) Add this code in the <head> section:
echo JMicrodata::htmlMeta($content = 'title', $property = 'name');
2) In whatever part of your code/file you want:
$microdata = JMicrodata::htmlMeta($content = 'title', $property = 'name');
$document = JFactory::getDocument();
$document->addCustomTag($microdata);
Documentation help
JMicrodata::htmlMeta() is used for output microdata semantics in a meta tag, this method does not add the meta tag in the <head> section.
I see you use $scope="itemprop", which is wrong, the scope is used to specify the Type of microdata, here you can find the full list of the available Types http://schema.org/docs/full.html
I suggest you to use an instance of JMicrodata, this way you don't need to worry that microdata is displayed properly.
$microdata = new JMicrodata('Article');
echo $microdata->content('title')->property('name')->display('meta');
In the <head> section add
<?php
$property="name";
$content="title";
echo JMicrodata::htmlMeta($content, $property, '', false);
?>
That will definitely get you the metadata.
Elsewhere if you did
$property="name";
$content="title";
$microdata = JMicrodata::htmlMeta($content, $property, '', false);
$document = JFactory::getDocument();
$document->addCustomTag($microdata);
That should do the trick.
My JQuery does not fire up the sanitize function.I need to take the value from the input field name ,and display it in path input field. Why isn't it working ? The page where all this code is written is called new_page.php , so when the ajax_request function gets fired it does not point to an external page but here on the same page. I use PHP 5.3 and HEIDISQL
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
include('conect.php');
if(($_POST)&&(!empty($_POST['name']))&&(!empty($_POST['path'])) ){
$name=$_POST['name'];
$path=$_POST['path'];
if(isset($_POST['sanitize'])) {
$title=$_POST['sanitize'];
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = str_replace('.', '-', $title);
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
echo $title;
}
mysql_query("UPDATE menus SET name='$name' , path='$path'");
}
?>
<html>
<head>
<script type="text/javascript" src="/javascript/jquery-1.8.2.min.js"> </script>
<script>
// create the XMLHttpRequest object, according browser
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
// sends data to a php file, via POST, and displays the received answer
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
// create pairs index=value with data that must be sent to server
var the_data = 'sanitize='+document.getElementById('name').innerHTML;
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
</script>
</head>
<body>
<form action="<?php $_PHP_SELF ?>" method="post">
<label for="nume">Name</label><input type="text" name="name" id="name" onchange="ajaxrequest('new_page.php', 'path')" />
<label for="cale">Path</label><input type="text" path="path" id="path" />
<input type="submit" name="submit"/>
</form>
</body>
</html>
As already mentioned, you cannot invoke PHP functions using JavaScript because one is a server-side technology and the other is client-side technology and is only executed on the local browser.
The suggested approach for dealing with data, databases, and user input is to use an MVC architecture with ActiveRecord paradigm for data access. If done correctly, all your data should be sanitized within the active record model before committing to the database.
I know this is an old post but I think this will help people searching for this question.
As Zorayr said, PHP is a server-side based language and Javascript or derivatives are client-side. That's because you can not invoke PHP functions from the JS code.
But instead of call a function, you can fire the function with a processed form as you have in your code. The other way is to make a PHP Class and in the same file initialize it.
Example:
<?php
Class MyClass {
function __construct()
{
echo "hello world.";
}
}
$init = new MyClass();
?>
This way you can pass arguments and do whatever more clear.
In Joomla 2.5, the scripts below are loaded automatically.
<script src="/media/system/js/mootools-core.js" type="text/javascript"></script>
<script src="/media/system/js/core.js" type="text/javascript"></script>
<script src="/media/system/js/caption.js" type="text/javascript"></script>
<script src="/media/system/js/mootools-more.js" type="text/javascript"></script>
<script src="/templates/pswedge/js/jquery.min.js" type="text/javascript" defer="defer"></script>
I don't want to load these files. How can I remove these links?
I would not recommend you to change the core files of Joomla.But if you really need to that then you can try this:
Step to disable the preloaded script file in joomla template.
Step one: Using your favorite file editor, open for edit:
/libraries/joomla/document/html/renderer/head.php
Step one: Find this code at line 151 and update it to include the code with this :
// Generate script file links
foreach ($document->_scripts as $strSrc => $strAttr)
{
// Code to disable mootools for your site (still loads it for your admin)
$ex_src = explode("/",$strSrc);
$js_file_name = $ex_src[count($ex_src)-1];
$js_to_ignore = array("mootools-core.js","mootools-more.js","core.js","caption.js");
if( in_array($js_file_name,$js_to_ignore) AND substr_count($document->baseurl,"/administrator") < 1 AND $_GET['view'] != 'form')
continue;
$buffer .= $tab . '<script src="' . $strSrc . '"';
if (!is_null($strAttr['mime']))
{
$buffer .= ' type="' . $strAttr['mime'] . '"';
}
if ($strAttr['defer'])
{
$buffer .= ' defer="defer"';
}
if ($strAttr['async'])
{
$buffer .= ' async="async"';
}
$buffer .= '</script>' . $lnEnd;
}
After saving the changes above, clear the cache that you have set and test your Joomla website and your Joomla Admin Dashboard. If you view the source code,all the predefind files are not there.
Or
You can try like this to hide it from index.php in template. Just put this line before the <jdoc:include type="head" /> and make necessary changes as needed to the scripts.
<?php
$search = array('mootools-more.js', 'caption.js');
// remove the js files
foreach($this->_scripts as $key => $script) {
foreach($search as $findme) {
if(stristr($key, $findme) !== false) {
unset($this->_scripts[$key]);
}
}
}
?>
May one of these method work-
Method 1:
Put Before <jdoc:include type="head" />
$search = array('mootools', 'caption.js');
// remove the js files
foreach($this->_scripts as $key => $script) {
foreach($search as $findme) {
if(stristr($key, $findme) !== false) {
unset($this->_scripts[$key]);
}
}
}
//Method 2
in index.php of template
$parameter_script = 'scripts';
$headerstuff=$document->getHeadData();
reset($headerstuff[$parameter_script]);
foreach($headerstuff[$parameter_script] as $key=>$value){
unset($headerstuff[$parameter_script][$key]);
}
$document->setHeadData($headerstuff);
//Method 3
In the file directory /plugins/system create a new file called “removemootools.php” and insert the following code (you will need to register the plugin in the database, too).
class plgSystemRemoveMooTools extends JPlugin
{
public function onAfterDispatch()
{
$app = JFactory::getApplication();
if($app->isSite()) //Only ever remove MooTools from the client-side, never the admin side
{
//Repeat these three line for all js you want to exclude
$mootools = JURI::root(true).DS.'media'.DS.'system'.DS.'js'.DS.'mootools.js';
$document = JFactory::getDocument();
unset($document->_scripts[$mootools]);
}
}
}
I used this code to remove jquery files from the head ( Joomla! 3.3.1 )
<?php
//Remove jquery
$search = array('jquery', 'jquery.min.js');
// remove the js files
foreach($this->_scripts as $key => $script) {
foreach($search as $findme) {
if(stristr($key, $findme) !== false) {
unset($this->_scripts[$key]);
}
}
}
?>
<jdoc:include type="head" />