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);
Related
I'm recently doing a website for a school project. In order to organize my work, I create a tree folder that keeps all the work organized. It is similar like this:
Back-Office
Pages
Home
home_test1.php
home_test2.php
home_test3.php
Login
Folder_Login
login.php
logout.php
Resources
CSS
style_home.css
style_navbar.css
style_footer.css
JS
script_home.css
script_navbar.css
Sections
navbar.php
footer.php
After all, with the require() method available in PHP, I want to call the "navbar.php" file to the "home_test1.php", "home_test2.php" and "home_test3.php", but the CSS style that is connected with the file "navbar.php" ("style_navbar.php"), doesn't display.
I've tried to change the path of the CSS style in the file "navbar.php" when I require() to the other file ("home_test1.php") and the CSS style shows up, but wont display in other file with a different path. How can I make this work dynamically? Sorry for long post and bad English grammar.
Thank you in advance.
You need to set your css and js files with absolute path instead of relative path
$dir = realpath($_SERVER["DOCUMENT_ROOT"]);
<link rel="stylesheet" href="<?php echo $dir.'/resources/css/style_home.css'; ?>" >
Without physically seeing you code it is quite hard to debug however there is an "obvious" answer that I'll suggest as a starting point.
The important thing to remember is that PHP and HTML are processed in completely different places. PHP executes on the server and should be used to build a full HTML "document" which it gives to the client/browser. The client/browser then reads the document provided and renders it according to HTML standards.
Calling require() will tell PHP to get the file and slot its contents directly where it was called and as it is a CSS file it will need to sit within the style tags. With a lot of modern browsers, if you use require on a file outside of the html tags, the content will be dumped at the top of the screen or simply ignored due to invalid syntax.
Alternatively if you would like to simply use tell the browser to include the CSS file, you could use the good old method of using <link rel="stylesheet" href="/path/to/file">. It's good to know when and when not to use PHP.
PS: You have .css files in your JS directory.
In PHP, there is a global variable containing various details related to the server. It's called $_SERVER. It contains also the root:-
$_SERVER['DOCUMENT_ROOT']
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
<link rel="stylesheet" href="<?php echo $path.= '/Resources/CSS/style_navbar.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.
We have a couple of pages that require special care, jquery-ui will be called from external scripts which are going to "somehow" be added to the head section of an article.
I've attempted with jumi, however it isn't the best choice(including a js in stead of php would render it in html body), the only way I could add a javascript file was by including a php file which would echo a , but as one would imagine, this isn't elegant nor efficient in terms of performance.
Another attempt was, in stead of echoing a script, I've tried using:
<?php
$document = &JFactory::getDocument();
$document->addScript( "path/to/jsfile.js" );
?>
but it didn't work as I've expected, it seems that joomla creates the head section before this php script has the chance of being executed.
I've also gave easy header a go, however, it seems that it will include the files in all articles, which I do not wish since it will have a pretty big impact in terms of bandwidth and possible javascript issues down the road.
I'm farily new to joomla so anything that would provide some flexibility is good as an answer.
If something isn't unclear, please ask, I will try to answer the best I can.
Please note that I'm using joomla 1.7 and php5.
Jumi uses the onAfterRender event (looking at the 2.0.6 plugin) - by this time I think the <head> tag has already been written out, in-fact the whole document is already rendered.
You could try getting the document body and then searching for the closing tag </head> and inserting the script link before it. Something like this:
$myJS = "<script type='text/javascript' src='http://mysever.com/my.js'>"
$content = JResponse::getBody(); // gets the html in it's ready to send to browser form
$hdPos = strpos($content, '</head>');
$hdPos += 7; //move position to include the <head> tag
$bodyLen = strlen($content);
$content = substr($content, 0, $hdPos) . $myJS . substr($content, $hdPos, $bodyLen);
JResponse::setBody($content);
NB: This is untested and I don't use Jumi these days but it should be close.
You didn't have to go through all this!
Go to: extensions -> template manager -> templates tab (its on "styles" by default) -> go to your template and click on "edit HTML". You'll be able to add your code directly in the header, and it will be loaded in all the pages.
A bit more elegant way is to define a function that does what you want in the header - and call it from the body of the specific article you want.
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
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