开发者

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

开发者 https://www.devze.com 2023-01-08 04:26 出处:网络
I\'m working out a process to save actions that o开发者_StackOverflow社区ccur 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,

I'm working out a process to save actions that o开发者_StackOverflow社区ccur 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

0

精彩评论

暂无评论...
验证码 换一张
取 消