CodeIgniter - pass variables to CSS - php

I'm rewriting website on Code Igniter, and i need to load external TTF. MySQL db points path to that TTFs. Can I pass somehow these variables to CSS and make foreach loop to 'loads' these fonts.
I tried
$this->load->vars($data);

First, deal with serving dynamic CSS. My site has a controller called "resource" which allows me to serve CSS, JS, etc. (maybe images in the future). It loads views based upon the segments passed to it in the url.
So, when http://mysite.com/resource/css/main.css is requested:
My Resource controller (.../controllers/resource) handles any specifics of data handling (as is general with an MVC controller). It then loads:
A generic view: ".../views/resources/css.php", passing it the name of the desired css file. This view prints out the header, specifying the Content-Type (important!) and any other generic stuff. Then it proceeds to load:
The actual CSS file specified, here ".../views/resources/css/main.css.php".
It's a little overkill, but allows for a lot of flexibility, like you sound like you need.
Controller:
...
$segments = $this->uri->segment_array();
array_shift($segments); // remove the first two
array_shift($segments);
$content['stylesheet'] = $segments[0] . ".php"; //e.g. main.css.php
$content['data'] = array(); //Font data, etc
$this->load->view('resources/css.php', $content);
..
Generic resources/css.php
This loads up the actual .css.php stylesheet
<?php header("Content-Type: text/css"); // This is key! ?>
/* MySite CSS File (c) 2011 bla bla */
<?php
$this->load->view("resources/css/$stylesheet", $data);
echo "\n";
?>
Specific resources/css/main.css.php
<?php echo "/* I can use PHP in my CSS! */\n"; ?>
body { background-color: <?=$data['bg_color']?>; }
p { font-family: <?=$data['p_font_fam'];?>; }

You probably need to understand how you retrieve data from db and how you display them:
http://codeigniter.com/user_guide/database/index.html
good luck
EDIT:
what you need is probably something like that:
after you have retrieved the links from database and let's say you called them $ttf_links
<?php
foreach($ttf_links as $link){
echo "<link rel='stylesheet' type='text/css' href={$link['row_name']} media='screen' />"
}
?>
and then call the fonts you need in your css

Passing variables to a CSS doesn't work for as far as I know.
I have read something about CSS templating with PHP, but I can't find the link anymore. Will update this answer as soon as I found the link. But you could look for it yourself as well.
Update
Found it!: http://www.barelyfitz.com/projects/csscolor/

The easiest way I see you doing this is with file level CSS and changing values the usual way.

A workaround would be to use CSS in the page itself to load the fonts.

Here is the answer , I have implemented this and works fine
https://ellislab.com/forums/viewthread/220105/#1014374

Related

Adding and styling external file

There is a file on another site that I do not own, with a URL in the following format:
http://example.com/path/with/some/variables
I want to include this file in one of my own pages. I could use iframe to do this, but I also want to change the CSS of something within the included file. To my knowledge, I can't do this with this method.
However, I can't seem to be able to successfully add this via PHP either, with something like:
<?php include 'http://example.com/path/with/some/variables'; ?>
I'm not sure what other methods exist that can do this, but surely this must be possible.
Also, I'm aware of the security implications of using include in a situation like this.
Use readfile:
<?php readfile('http://example.com/path/with/some/variables'); ?>
Yeah, security limitations won't allow you do do this directly in an iframe, by manipulating the DOM of the iframed file.
To do it in PHP, you could create a PHP script to read the contents of the URL and add an external CSS file that you've created, to override whatever you want. So:
myreader.php:
$contents = file_get_contents("http://example.com/path/with/some/variables");
$contents = preg_replace("/<head>/", "<head>\n<link rel='stylesheet' type='text/css' href='mystyle.css'>", $contents, 1);
echo $contents;
and then create mystyle.css:
body {
color : red !important;
}
Finally, either just point your browser to myreader.php, or if you still want it in an iframe, point the iframe src to myreader.php.
PS: Stealing is wrong :)
You can use file_get_contents
<?php $content = file_get_contents('http://example.com/path/with/some/variables'); ?>
Here is the documentation file_get_contents

Using OO PHP in CSS

tl;dr - I'd like to know if it is possible to pass an object into a PHP file with CSS headers, such that I can use this object to manipulate various CSS attributes.
What I'm attempting to do, is allow my PHP/CSS file to interact with the other objects/php files in the webpage, e.g. menu item objects. My ultimate goal is to use PHP in the CSS file to count the number of menu items, and apply the appropriate width value in order to space them out evenly on the page.
I use a very simple color based example below to demonstrate my understanding so far...
I understand that for basic usage of PHP in a CSS file, one can do something like:
<?php header("Content-type: text/css");
$dkgreen = '#008400';
body {
background:<?=$white?>;
}
?>
I also understand that OO PHP can be used to achieve a similar thing, e.g.:
class css {
function __construct($args=array()) {
foreach($args as $key => $field) {
$this->{"$key"} = $args["$key"];
}
return $this;
}
}
$css = new css(
array(
bgcolor => '#00FF00',
fgcolor => '#000000',
)
);
body {
background: <?php echo $css->bgcolor; ?>;
color: <?php echo $css->fgcolor; ?>;
}
Results of experimentation
1) OO style
I firstly attempted to make my css class create a singleton object for the CSS, which I tried to retrieve using $css = css::singleton(), along with the getCss() function, instead of $css = new css(...). The idea was that I wouldn't simply initialise another css object which would be useless to me. Attempts to get the values for bgcolor and fgcolor using:
$css = css::singleton();
$css->getCss()->bgcolor;
were unsuccessful.
2) altering the href in the link tag à la style.php?bgcolor=00FF00&fgcolor=000000
This worked beatifully, when I could easily type $bgcolor = $_GET['bgcolor'];, but doesn't seem to me an elegant solution.
Ideally, I'd like to retain an Object-Oriented approach, but if that's not possible, I'll happily settle for a POST approach, (i.e. allow me to use $bgcolor = $_POST['bgcolor'];) to avoid filling up the source code with ugly parameters in the link tag.
I'd also wish to avoid creating multiple .css files, if that is at all possible.
Any tips?
Many thanks,
Owen.
The easiest way to do this is to make your CSS file a PHP file, and link to it.
<link href="style.php" rel="stylesheet" type="text/css" media="all" />
Then, you parse all your code and dump it out at the end.
$css = ''; # all of your compiled CSS after you do what you need to
header("Content-type: text/css");
print $css;
exit;
Now, your CSS is being parsed how you want it to be, and it's being served as CSS.
I don't think it's possible, and that doesn't fit the purpose of CSS.
Edit:
Well basically, CSS is suppose to contain data that apply a style on a well defined structure. So CSS should not even have variables ( this is a big debate ). The "good theorical way" to solve your problem is to generate html code with proper id and classes, so that you don't have to make any calculation using CSS: you only have to apply a style.
Furthermore:
CSS file are made to be cached. If they change all the time, you may have cache problem, or need to ask the file not to be cached. The you might need to generate inline CSS using PHP, but not a CSS file itself.

How to load a css in CodeIgniter?

I'm new to programming. I want to fetch the css saved in DB and load in a php file. I'm using CodeIgniter. After loading the css, I want to link to it as an external css. I tried following, but it is not working.
EDIT:
defaultCss.php is the file in which I want to load the css.
$strTemplate.="<link rel='stylesheet' type='text/css' href='".base_url()."user/defaultCss.php'>"
While, I view the page source it gives "Page not found" error.
Below are my controller and view code.
function loadDefaultCSS(){
$this->load->model('UserModel');
$this->UserModel->loadDefaultCSS();
}
View :
if(isset($strTemplateStyles) && $strTemplateStyles!="") {
echo $strTemplateStyles;
}
Model function :
function loadDefaultCSS($strTemplateStyles){
$data['strTemplateStyles']=$strTemplateStyles;
}
Why this is not working ? what is the issue ?
You can use template library for codeigniter.
It provides more flexibility for handling views, loading js and css files.
Also it provides an option for splitting the views into sections like header, content, footer etc. The template library link i have provided above is easy to use and integrate.
It also has very good documentation.
In the above template library the css and js files can be loaded as follows (write below code in controller) -
For loading css files -
$this->template->add_css('path to css file');
For loading js files -
$this->template->add_js('path to js file');
For detailed documentation you can refer above hyperlink.
Well the name of your controller action is loadDefaultCSS, so I would expect the URL for the generated stylesheet to be: (assuming your controller is indeed called User)
base_url()."user/loadDefaultCSS"
Does this work?:
$strTemplate .= '<link rel="stylesheet" type="text/css"
href="'.base_url().'"user/loadDefaultCSS">';
I can see a few strange things in your code:
You should not use .php in your CI URLS
How can your view possibly get the style of the user when you're not passing it to the view from your controller?
How do you know what user it concerns? I assume you have not posted all your code?
What happens if you actually open the stylesheet URL that you generate? Does it throw a 404? A CI error?
The Best way to load css is to pass css paths from controller to view and render it from view in large application we its not good practice to load everything in header it can cause performance issue
login_view.php / view
css code
<?php
if(!empty($css_files)){
foreach ($css_files as $css_path) {
?>
<link rel="stylesheet" href="<?php echo $css_path;?>">
<?php
}
}
?>
login.php /controller
$data['css_files'] = array(
base_url('assets/bootstrap/css/bootstrap.min.cs'),
base_url('assets/plugins/iChecksquare/blue.css'),
'https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css');
$this->load->view('login',$data);
same technique you can use for javascript libs
note that sequence of the files are sensitive

Cakephp, dynamically write variables into css file upon load of view?

I'm working out a process to save actions that occur from jquery in my view in cakephp.. I figure an easy way to load the saved values, such as the width and height for a DIV, would be to have cakephp echo a variable as their width / height in the css file, much the same way it would do this in the view file.. I guess I'm not sure exactly where to look for info on this, if its in the cakephp cookbook I guess I'm missing it as I don't see how to do it in there.. any advice is appreciated.
This is actually pretty easy (and powerful), and can be done without the aid of CakePHP.
First, make a new file in your webroot called css.php. At the top of that file put the following:
<?php header("Content-Type: text/css"); ?>
Now, link to this file in the head of your layout, just as you would a normal CSS file.
<link rel="stylesheet" href="/path/css.php" type="text/css" />
And there you have it, a dynamic CSS file. You can pass information to it like so:
<link rel="stylesheet" href="/path/css.php?c=red&fw=700" type="text/css" />
CLARIFICATION: To access the variables mentioned above, you would use the $_GET variable in the CSS file. Take a look at the link tag above. To access those variables in the css file, you would do something like this:
.class {color:<?php echo $_GET['c']; ?>;font-weight:<?php echo $_GET['fw']; ?>;}
UPDATE: After viewing the link you posted about the CakePHP HTML Helper, I realized that there is a better way to do this if you intend to pass a lot of variables to the css file.
Create a new model and controller called DynamicStyle and DynamicStylesController (or something similar). Then, make a new layout file called css.ctp that all of this controller's views will use. Declare the content-type header statement in that layout file.
The last step would be to link to a method in that controller from the head of your standard layout header.
Now you could make a database table of css rules and use those with the HTML helper in the css view.
I just realized CakePHP has something for this as well:
http://book.cakephp.org/view/1440/style
So this may come in handy for anyone who comes across this in the future

drupal_add_css not working

I need to use drupal_add_css to call stylesheets onto single Drupal 6 pages. I don't want to edit the main theme stylesheet as there will be a set of individual pages which all need completely new styles - the main sheet would be massive if i put it all in there.
My solution was to edit the page in PHP editor mode and do this:
<?php
drupal_add_css("/styles/file1.css", "theme");
?>
<div id="newPageContent">stuff here in html</div>
But when I view source, there is nothing there! Not even a broken CSS link or anything, it's just refusing to add the CSS sheet to the CSS package put into the page head.
Variations don't seem to work either:
drupal_add_css($path = '/styles/file1.css', $type = 'module', $media = 'all', $preprocess = TRUE)
My template header looks like this, I've not changed anything from the default other than adding a custom JavaScript.
<head>
<?php print $head ?>
<title><?php print $head_title ?></title>
<?php print $styles ?>
<?php print $scripts ?>
<script type="text/javascript" src="<?php print base_path() ?>misc/askme.js"></script>
<!--[if lt IE 7]>
<?php print phptemplate_get_ie_styles(); ?>
<![endif]-->
</head>
Why is this function not working?
It is not quite clear where you are selecting the template that you have in your example. If you are selecting it from a module then you can just use drupal_add_css in the module rather than the template.
If you have your own theme you can use template_preprocess_page and put logic in there to add the relevant CSS (you can also use it to select the template to use).
I have noticed something weird and it might fix your problem:
drupal_add_css( drupal_get_path('theme','themname') . '/working.css','module' ,'all' , false );
drupal_add_css( drupal_get_path('theme','themname') . '/path/to/folder/notworking.css','module' ,'all' , false );
The first one will work ebcause the style it in the main them folder
The second line will not work because the style is in a sub folder !
Edit:
i think it did not work because i did not write the path the the style file properly :S so please disregard my answer
drupal_add_css( drupal_get_path('theme','test') . '/pages/subpage/style.css','theme');
is working
This function wont work in templates. The reason is that the variable $styles which will hold all the stylesheet html will already have been generated at this point, so drupal_add_css wont work as it adds to that. if you want to do this in your theme, you would probably have to add the css file manually
<link rel="stylesheet" ... />
The other way would be to use drupal_add_css in a module, but you might have a hard time adding the correct css files on the pages you want.
It's possible to use drupal_add_css() inside your template.php file; this page has a good example of how to do just that.
Thanks for the link, wyrmmage. That's very useful. I think the rest of the code in the page is unneccessary. You probably just need these since drupal 6 already automatically check for file existence:
drupal_add_css(path_to_theme() . '/css/yourcss.css', 'theme');
// Add the following to regenerate $styles.
// This is needed for template_preprocess_page() since css is already generated at this point.
$variables['styles'] = drupal_get_css();
Answer was very much to use the CSS Injector module - great little addon!
Here is an excerpt from its project page:
Allows administrators to inject CSS into the page output based on configurable rules. It's useful for adding simple CSS tweaks without modifying a site's official theme. The CSS is added using Drupal's standard drupal_add_css() function and respects page caching, etc. The 2.x brach leverages CTools so CSS can be included with Feature changes (ie. CSS that improves the look of a View can be packaged with the View).
This code inside template.php works for me:
function alagna_preprocess_page(&$vars) {
drupal_add_css(path_to_theme() . '/header_1.css', 'theme');
$vars['css'] = drupal_add_css();
$vars['styles'] = drupal_get_css();
}
explained:
alagna is the theme name
header_1.css is the css file required.
drupal_add_css is expecting a path relative to base path whereas drupal_get_path does not return the path relative to base path.
global $base_path;
drupal_add_css($base_path . drupal_get_path('module / theme','name') . "/styles/file1.css", "module / theme");
You can choose between module and theme accordingly.
Try this
common.inc drupal_get_css($css = NULL)
Parameters
$css: (optional) An array of CSS files. If no array is provided, the default stylesheets array is used instead.
$css = $vars['css'];
// unset the system css files
$unset_css = array
'modules/system/system.css',
'modules/system/system-menus.css',
);
foreach($unset_css as $css_f) {
if(isset($css['all']['module'][$css_f])) {
unset($css['all']['module'][$css_f]);
}
}
// add css
$css['all']['theme'][drupal_get_path('theme', 'openpublish_theme') . '/css/style.css'] = true;
$vars['styles'] = drupal_get_css($css);

Categories