Could someone please advise me on the current methods available for using PHP in a CSS file in CakePHP 2.x
I have currently separated my stylesheet into a php file and wish to parse my data via the URL but I cannot seem to work out how to link it using
$this->Html->css('dynamic-stylesheet')
as it always appends .css to the name.
Your help is much appreciated.
You can generate the tag by using HtmlHelper::meta()
echo $this->Html->meta(array(
'link' => '/css/test.php',
'rel' => 'stylesheet',
'type' => 'text/css'
));
Note that you need to explicitly direct it to the /css directory, as you are no longer using a helper method specifically for CSS.
Looking at the Html helper file in the CakePHP library located at lib/Cake/View/Helper/HtmlHelper.php, check out line 427, looks like the .css extension is set automatically unless there are two slashes in the CSS file name. I GUESS that is to catch external resources?
From the aforementioned library file:
if (strpos($path, '//') !== false) {
$url = $path;
} else {
$url = $this->assetUrl($path, $options + array('pathPrefix' => CSS_URL, 'ext' => '.css'));
if (Configure::read('Asset.filter.css')) {
$pos = strpos($url, CSS_URL);
if ($pos !== false) {
$url = substr($url, 0, $pos) . 'ccss/' . substr($url, $pos + strlen(CSS_URL));
}
}
}
So this..
echo $this->Html->css('http://whatever.com/css/dynamic-stylesheet.php');
Would render the dynamic-stylesheet.php file rather than defaulting to 'dynamic-stylesheet.css.
Not sure that is what this was intended for but maybe that file will help you.
Related
I would like to create a file based on template Twig (and one parameter).
My file generated correctly with replace variable with my data. But if I change data my controller symfony generated always the same file with the same content.
My varDumper content (the text/plain character represent file) is good. It's change always with change variable content. But the writing file always generate the same content...
PHP seems do not caching with fwrite ou file_put_contents function but my content never change. I also disable caching for twigEngine but same result.
Can you help me to writing file with good last content.
All code is in a controller symfony. I keep comment code for your understanding all my test :
public function createEntityAction()
{
$rootDir = $this->getParameter('kernel.root_dir');
$templateDir = $rootDir . '/../src/CmsBundle/Resources/views/Entity/templateFile/';
$filename = 'test.php';
$pathFile = $templateDir . $filename;
$twigEngine = $this->get('twig');
$twigEngine->setCache(false);
$twigEngine->disableAutoReload();
// $loader = new Twig_Loader_Filesystem($templateDir);
// $twig = new Twig_Environment($loader, [
// 'cache' => '/path/to/compilation_cache',
// 'cache' => false,
// ]);
$baseTemplate = $twigEngine->loadTemplate('#Cms/Entity/templateFile/baseEntity.html.twig');
$script = $baseTemplate->render(['slug' => 'product-333']);
\Symfony\Component\VarDumper\VarDumper::dump($script);
if (file_exists($pathFile))
{
clearstatcache(true);
$ret = unlink($pathFile);
\Symfony\Component\VarDumper\VarDumper::dump($ret);
}
$file = fopen($pathFile, 'w+');
fwrite($file, $script);
fclose($file);
// file_put_contents($pathFile, $script);
return $this->render('#Cms/Entity/create.html.twig', []);
}
The final file content is always the same if I change the "slug" variable.
It looks to me like you're missing a variable in your controller. There should be something like this createEntityAction($slug), then this line should be $baseTemplate->render(['slug' => $slug); Right now it is doing exactly what you are telling it, you have a hard coded string for the slug...
If you post your controller definition it would help (annotations or yaml)
How can we setup multiple themes in codeigniter as in Magento?
I want to do this in HMVC CI.
I want to add theming feature with my development. I am using HMVC setup from Codeigniter HMVC
This is properly set and works fine.
This is a great development approach.
Here I am trying to add theme feature with this code, that could be controlled from admin panel.
/themes/themeName/templates/
/themes/themeName/modulesName/View
Approach is if view file not found in themes folder, it should come from
application/modules/moduleName.
What changes I have to do with this script ?
Can anyone suggest me what modification nee to do with this code?
Perhaps I misunderstood but why not extend CI's Loader class and add a theme function? I did this recently and it works great.
public function theme($view, $theme, $vars = array(), $return = FALSE) {
// Check if extension was specified. If not, add .php
$ext = pathinfo(APPPATH . $theme, PATHINFO_EXTENSION);
$view_file = ($ext == '') ? $view.'.php' : $view;
// Verify whether or not the requested theme file exists and set the template directory path prefix accordingly
if(file_exists(APPPATH . "views/store/theme/$theme/$view_file")) {
$this->_ci_view_paths = array(APPPATH . "views/store/theme/$theme/" => true);
}
else {
$this->_ci_view_paths = array(APPPATH . "views/store/theme/default/" => true);
}
return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
}
Normally I use the Zend Framework and this is something I miss in Lithium. Partials. There is a render method in the view where you can use 'elements' which is the closest I got.
<?php $this->_render('element', 'form); ?>
This does work, however it requires that the form.html.php file is in the /views/elements folder. Is it possible to let it search in another path? Like /views/users/ so it gets the file /views/users/form.html.php.
I have tried the following, since I found out that the render method does accept an options argument wherein you can specify a path. So I made an Helper to fix this problem for me.
namespace app\extensions\helper;
use lithium\template\TemplateException;
class Partial extends \lithium\template\Helper
{
public function render($name, $folder = 'elements', $data = array())
{
$path = LITHIUM_APP_PATH . '/views/' . $folder;
$options['paths']['element'] = '{:library}/views/' . $folder . '/{:template}.{:type}.php';
return $this->_context->view()->render(
array('element' => $name),
$data,
$options
);
}
}
However it still only searches in the /view/elements folder, not in the path I specified.
Is there something I am doing wrong?
Why using plugins when this stuff can hopefully be done by Lithium :-)
I don't know Zend, but here is an exemple to configure elements default paths differently, to load them from the related view folder, instead of a shared path.
And let's add one more thing: we want to differentiate elements/partials from a normal view, by appending un underscore to the name of the file (mimic Rails partials)
First, reconfigure Media during the bootstrap process (config/bootstrap/media.php)
Media::type('default', null, array(
'view' => 'lithium\template\View',
'paths' => array(
'layout' => '{:library}/views/layouts/{:layout}.{:type}.php',
'template' => '{:library}/views/{:controller}/{:template}.{:type}.php',
'element' => array(
'{:library}/views/{:controller}/_{:template}.{:type}.php',
'{:library}/views/elements/{:template}.{:type}.php'
)
)
));
Then, use it
Suppose a controller Documents. Call on a view:
<?= $this->_render('element', 'foo', $data, array('controller' => 'documents')); ?>
This will look for a file inside views/documents/_foo.html.php and if doesn't exists, fallback to /views/elements/foo.html.php
This kind of simple re-configuration of framework defaults, can be done in Lithium for a bunch of stuffs (default controllers paths to create namespaces, views paths, libraries, etc ...)
One more example to re-maps your template paths so you can have stuff like pages/users_{username}.php instead of the Lithium default:
https://gist.github.com/1854561
Fixed it. Works like a charm. Zend like Partials in Lithium.
<?php
namespace app\extensions\helper;
use lithium\template\View;
class Partial extends \lithium\template\Helper
{
public function render($name, $folder = 'elements', array $data = array())
{
$view = new View(array(
'paths' => array(
'template' => '{:library}/views/' . $folder . '/' . $name . '.{:type}.php'
)
));
return $view->render('all', $data);
}
}
Can be used in templates like:
<?php echo $this->partial->render('filename', 'foldername', compact('foo', 'bar')); ?>
There is a plugin for partials. https://github.com/dmondark/li3_partials
I create a plugin for WordPress that requires two files to be exists in order to operate normaly.
The first file is defined as a file system path and the second file is defined as a URL.
Let's say the first file is that:
/home/my_site/public_html/some_folder/required_file.php
and the second file is that:
http://www.my_site.com/some_folder/required_url_file.php
Note that both files are not the same file into the file system. The required_file.php has other content than the required_url_file.php and they act absolutly diferent
Any idea on how to validate the existance of both files ?
You can check both:
$file = '/home/my_site/public_html/some_folder/required_file.php';
$url = 'http://www.my_site.com/some_folder/required_url_file.php';
$fileExists = is_file($file);
$urlExists = is_200($url);
$bothExists = $fileExists && $urlExists;
function is_200($url)
{
$options['http'] = array(
'method' => "HEAD",
'ignore_errors' => 1,
'max_redirects' => 0
);
$body = file_get_contents($url, NULL, stream_context_create($options));
sscanf($http_response_header[0], 'HTTP/%*d.%*d %d', $code);
return $code === 200;
}
Based on Maor H. code sample, here is a function I am using in my plugins:
/**
* Check if an item exists out there in the "ether".
*
* #param string $url - preferably a fully qualified URL
* #return boolean - true if it is out there somewhere
*/
function webItemExists($url) {
if (($url == '') || ($url == null)) { return false; }
$response = wp_remote_head( $url, array( 'timeout' => 5 ) );
$accepted_status_codes = array( 200, 301, 302 );
if ( ! is_wp_error( $response ) && in_array( wp_remote_retrieve_response_code( $response ), $accepted_status_codes ) ) {
return true;
}
return false;
}
I've made this a method in a helper class, however putting this in your theme's functions.php file should make it generally accessible everywhere. However you should always be writing in classes and instantiating them. It is much better for isolating your plugin and theme functionality.
With this in place you can simply use:
if (webItemExists('http://myurl.com/thing.png')) {
print 'it iexists';
}
Most often you will be using WordPress calls to access all items via a relative or fully qualified URL. If you have a relative reference to something such as /uploads/2012/12/myimage.png you can convert those to a fully qualified URL v. a WordPress relative URL by simply adding get_site_url(). $string when calling the webItemExists() function.
As for validating the URL, none of these answers are considering the correct, WordPress way to carry out this task.
For this task wp_remote_head() should be used.
Here's an article I've written about How To Check Whether an External URL Exists with WordPress’ HTTP API. Check it out and figure out how it works.
$file_exists = file_exists($path);
$url_accessable = http_get($url, array("timeout"=>10), $info); // should not be FALSE
$status_code = $info['response_code'] //should be 200
This seems to work for me:
function url_file_exists($url) {
$context = stream_context_create(array('http' =>array('method'=>'HEAD')));
$fd = #fopen($url, 'rb', false, $context);
if ($fd!==false) {
fclose($fd);
return true;
}
return false;
}
If you have PECL http_head function available, you could check if it returns status code 200 for the remote file.
To check if you can access the local file, could use file_exists, but this does not grant that you will be able to access that file. To check if you can read that file, use is_readable.
To check if a file exists, use the file_exists method.
As of PHP 5.0.0, this function can also be used with some URL
wrappers. Refer to Supported Protocols and Wrappers to determine which
wrappers support stat() family of functionality.
if(! (file_exists($url1) && file_exists($url2)) ) {
die("Files don't exist - throw error here.");
}
// Continue as usual - files exist at this point.
remote:
$file = 'http://www.my_site.com/some_folder/required_url_file.php'
if ( #fclose(#fopen($file,"r")) ) echo "File exists!";
local:
$file = '/home/my_site/public_html/some_folder/required_file.php';
if ( is_file($file) ) echo "File exists!";
Use function file_exists()
file_exists('http://www.my_site.com/some_folder/required_url_file.php');
will get you results as True or false.
Checking if a file exists:
if (file_exists('path/to/file.txt')) {
echo "File exists!";
} else {
echo "File doesn't exist.";
}
Checking if a URL is valid:
$data = #file_get_contents("http://url.com/");
if (!$data) {
echo "URL not valid.";
} else {
echo "URL is valid.";
}
Notes:
Ideally you shouldn't try and predict the filesystem. Whilst methods such as file_exists are very helpful, they shouldn't be relied upon and instead you should attempt to write to files, read from them, etc, and then catch and handle any exceptions or errors that occur.
Although I don't think the question was as good as it could be, let me try to explain better here.
I have a site using SMARTY 3 as the template system. I have a template structure similar to the below one:
/templates/place1/inner_a.tpl
/templates/place1/inner_b.tpl
/templates/place2/inner_b.tpl
/templates/place2/inner_c.tpl
/templates/default/inner_a.tpl
/templates/default/inner_b.tpl
/templates/default/inner_c.tpl
These are getting included on the parent template using
{include file="{$temp_folder}/{$inner_template}"}
So far great. What I wanted to do is having a default for, in the case that the file {$temp_folder}/{$inner_template} does not exists, it uses the equivalent file at default/{$inner_template}.
i.e. If I do {include file="place1/inner_c.tpl"}, since that file does not exists it in fact includes "default/inner_c.tpl"
Is it possible?
You'll have to do it in php, smarty doesn't have a way to check if a file exists.
You could write your own template handler too.
<?php
// put this function somewhere in your application
function make_template ($resource_type, $resource_name, &$template_source, &$template_timestamp,
&$smarty_obj)
{
if( $resource_type == 'file' ) {
if ( ! is_readable ( $resource_name )) {
// create the template file, return contents.
$template_source = "This is a new template.";
require_once SMARTY_CORE_DIR . 'core.write_file.php';
smarty_core_write_file( array( 'filename'=>$smarty_obj->template_dir . DIRECTORY_SEPARATOR . $resource_name, 'contents'=>$template_source ), $smarty_obj );
return true;
}
} else {
// not a file
return false;
}
}
// set the default handler
$smarty->default_template_handler_func = 'make_template';
?>