styling css with php from constructor - php

I'm very beginner to php so I'm trying to understand the following:
class Style{
public $fontsize;
public $fontcolor;
public $bgcolor;
function __construct($fontsize,$fontcolor,$bgcolor){
$this->fontsize="font-size: $fontsize";
$this->fontcolor="color: $fontcolor";
$this->bgcolor="background-color: $bgcolor";
}
}
$setStyle = new Style("12px","red","blue");
$output = <<<EOT
$setStyle->fontcolor; <!-- this prints -> color: red; --->
<div style="<?php $setStyle->fontcolor; ?>">This is test for php</div><!---but why not here, it's not working---->
EOT;
echo $output;
The question is clearly defined in the code above with comments why css style is not working.

Change your div to this:
<div style="{$setStyle->fontcolor}">This is test for php</div>
Since your code is already in a <?php ?> block, you don't need to add it again unless you're going to put it outside a <?php ?> block, and; if you do put it outside, do it like this:
<div style="<?php echo $setStyle->fontcolor; ?>">This is a test for php</div>

Can you try this, replaced
style="<?php $setStyle->fontcolor; ?>"
into
style="$setStyle->fontcolor"
Code:
$output = <<<EOT
$setStyle->fontcolor <!-- this prints -> color: red; --->
<div style="$setStyle->fontcolor">This is test for php</div><!---but why not here, it's not working---->
EOT;
echo $output;

Related

WordPress - How to use PHP inside HTML injecting function?

I have a function that injects HTML code, the function looks like this:
function page_content() {
echo <<<HTML
<body>
<?php ?> //this won't work
</body
<style>
</style>
HTML;
}
Is there any way to write PHP code inside this HTML injection function?
This function is used for replacing the default WP Dashboard, but writing just HTML and CSS is limiting me totally :( Thanks
edit:
I have resolve this by breaking the HTML into two parts like this:
function page_content() {
echo <<<HTML
<body>
<div class="test">
<p>Body</p>
<p>Body</p>
<p>Body</p>
HTML;
echo do_shortcode('[contact-form-7 id="86" title="My Form"]');
echo <<<HTML
<p>Body</p>
<p>Body</p>
<p>Body</p>
</div>
</body>
<style>
.test {
display: flex;
flex-direction: column;
}
</style>
HTML;
}
If there is any better or easier way of doing this please let me know. I'm only learning, so always happy to learn the best ways of solving things in PHP. Thanks guys!
You can write like this.
<?php
function page_content() {
$output = 'HTML
<body>';
$output .= write php code here;
$output .=' </body
<style>
</style>
HTML';
echo output;
}
?>
I wrote like this so that you can understand easily but if you get used to combining HTML with php, you can just write together using .' and '. lol
<?php
function page_content() {
$output =
'HTML
<body>' . $write_anything_with_php .' </body>
<style>
</style>
HTML';
echo output;
}
?>

get_template_part appears to be removing a class on h2

I'm working on a custom template part that includes an h2 with the classes "sectionmarker" and "bodycontent", like this:
<h2 class="sectionmarker bodycontent">Title</h2>
When I call get_template_part() on a page, the output I'm getting is:
<h2 class="bodycontent">Title</h2>
For some reason, it seems not to like "sectionmarker". I even switched the order of the two classes, like this:
<h2 class="bodycontent sectionmarker">Title</h2>
And I get the same output with only the bodycontent class applied. What's going on here?
Full template content:
<?php
$abstract=get_post_field('post_content',224);
$news=get_posts(array(
'post_type'=> 'news'
));
$newsdata=array();
foreach ($news as $n) {
$item=new stdClass();
$item->title=get_the_title($n->ID);
$item->date=get_the_date("",$n->ID);
$item->content=get_field('more_info',$n->ID);
array_push($newsdata,$item);
}
$newsdata_json=json_encode($newsdata);
?>
<script type="text/javascript">
console.log(<?php echo $newsdata_json ?>);
</script>
<?php
echo $abstract;
if(count($newsdata)>0){
?>
<h2 class="sectionmarker bodycontent" >News</h2>
<?php foreach ($newsdata as $newsitem) { ?>
<h4 class='datemarker bodycontent'><?php echo $newsitem->date ?></h4>
<p class='newstext bodycontent'><?php echo $newsitem->title ?></p>
<?php } } ?>
and here's the call I'm making (in home.php):
get_template_part('custom-home-template',null,array());
Nevermind! I just remembered I have some JavaScript that's changing the h2 classes on load.

using image that I have its url in database for background image

I'm designing a web page to show some commodity
results (such Model, price, Comment) for every Commodity is a database
and I call theme to show in each Commodity (it while be shown in a div)
I wanna to set backgrounds for each div (it saved in database and every Commodity have one background-image)
please tell me whats the true syntax for this div s
for example I wrote this code:
<div class="commodities"> <style>.commodities{ background-image:<?php $Images[$i]?>} </style>
<?php
echo "Model:";
echo $Models[$i];
echo "<br><br>";
echo "Price: ";
echo $Prices[$i];
echo "<br><br>";
echo $Comments[$i];
?>
</div>
please help me to fix this part of code: { background-image:}
You have to do this:
<div class="commodities" style="background-image: url('<?php $Images[$i]?>');">
<?php
echo "Model:";
echo $Models[$i];
echo "<br><br>";
echo "Price: ";
echo $Prices[$i];
echo "<br><br>";
echo $Comments[$i];
?>
</div>
If you put < style > tags in the < body > (put it on the < head > tags) you are doing nothing ;)
Instead use style property. ;)
Apart you are forgetting to use url tag on the background-image property. ;)
You are missing two keywords, scoped and url. See e.g. http://www.w3schools.com/tags/att_style_scoped.asp and http://www.w3schools.com/cssref/pr_background-image.asp.
use inline css.
<div style="background-image: url(<?php echo $variable_name; ?>);">
or
use internal css.
<style type="text/css">
.logo {
background: #FFF url(<?php echo $variable_name; ?>);
}
</style>

Defining html code inside PHP variables

I want to include html code inside php variables.
I remember there was a way to define html code inside a php variable, something similar to this:
<?php $my_var = { ?>
<div>SOME HTML</div>
<?php } ?>
I found it on PHP.net but I can't find it now.
There was something else instead of the "{" but I don't remember exactly.
I am looking to directly write the html code like above, so NOT like this: $my_var = '<div>SOME HTML</div>';
Any ideas?
Try this:
<?php ob_start(); ?>
<div>HTML goes here...</div>
<div>More HTML...</div>
<?php $my_var = ob_get_clean(); ?>
This way you will retain syntax highlighting for HTML.
<?php
$my_var = <<<EOD
<div>SOME HTML</div>
EOD;
?>
It's called heredoc syntax.
Save your HTML in a separate file: example.html. Then read in the contents of the file into a variable
$my_var = file_get_contents('example.html');
If you don't care about HTML syntax highlighting you could just define a normal variable. You don't have to escape HTML either because PHP lets you use single quotes to define a variable, meaning you can use double quotes within your HTML code.
$html = '
<p>
<b><i>Some html within a php variable</i><b>
</p>
<img src="path/to/some/boat.png" alt="This is an image of a boat">
' ;
Works perfectly for me, but it's a matter of preference and implementation I guess.
If you are going to be echoing the content then another way this can be done is by using functions,
this also has the added benefit of programs using syntax highlighting.
function htmlContent(){
?>
<h1>Html Content</h1>
<?php
}
htmlContent();
?>
To define HTML code inside a PHP variable:
1) Use a function (Ref: #RedSparr0w)
<?php
function htmlContent(){
?>
<h1>Html Content</h1>
<?php
}
?>
2. Store inside a variable
$var = htmlContent();
To add to the few answers that mention using a function in the var. may I suggest an anonymous function. I'm not a php wizard so please correct me if I'm wrong, but I would imagine it working something like the following:
<?php
$my_var = function(){
?>
<div>SOME HTML</div>
<?php
};
// Display content
$my_var();
To extend this even further, if other php content is needed in the html it could be passed in a few different ways.
$method1 = "Title"; // Will be the same for every instance
$method2 = "default content"; // Can change for each instance
$my_var = function($unique=$method2/*set default*/) use ($method1){
?>
<h1><?php echo $prop1; ?></h1>
<div><?php echo $unique; ?></div>
<?php
};
// Display content
$my_var();
//returns
Title
default content
$my_var("Some unique content");
//returns
Title
Some unique content
How can I use this array, in the tr, td section of html and assign this html content to a php variable $data.
$student = [
'saurabh' => 26,
'John' => 20,
'Ross' => 30
];
<!DOCTYPE html>
<html>
<head>
<style>
table{
border: 1px solid black;
}
.lft {
padding: 0px 80px 10px 5px;
}
td {
border-bottom: 2px solid black;
}
</style>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Saurabh</td>
<td>26</td>
</tr>
</table>
</body>
</html>

PHP foreach, CSS and jQuery script.. How to interact?

i'm trying to use a jQuery show/hide script on a PHP file, and it goes like this:
<?php
foreach ($empresas as $empresa) {
echo "<style type='text/css'>
.$empresa[teaserid] {
width:100%;
background-color: #CCC;
color: #000;
margin-top:10px;
border:1px solid #CCC;
position:relative;
vertical-align:middle;
}
.showhide$empresa[teaserid] {
display:none;
}
</style>";
echo '<script type="text/javascript">';
echo ' $(document).ready(function(){ ';
echo ' $(\".$empresa[teaserid]\").hide(); ';
echo ' $(\".showhide$empresa[teaserid]\").show(); ';
echo ' $(\".showhide$empresa[teaserid]\").click(function(){ ';
echo ' $(\".$empresa[teaserid]\").slideToggle(), 500; ';
echo ' }); ';
echo ' });';
echo '</script>';
echo "<a href='#' class='showhide$empresa[teaserid]'>$empresa[titulo]</a><br />
<div class='$empresa[teaserid]'>
TEST</div>";
}
?>
So, what I need is a foreach in php that echoes new CSS values and a new jQuery script. because each DIV needs different CSS and jQuery to relate and be able to show and hide its content. This echoing didn't work. The CSS goes ok, but the jQuery doesn't with the PHP $strings. What can I do?
Or there's a simpler way to do this? A jQuery function that relates to any current div alone ?
Thanks anyone who helps me in this one..
Worth mentioning:
You can create a settings object to keep your variables in. For example:
Your php:
<?php
$settings = array( 'settingA' => 'something',
'settingB' => 'something else',
'wat' => 9001 );
?>
Keep your JS in your js file - scripts.js, whatever. But you can add this to your html file:
<script>
var settings = <?php echo json_encode( $settings ) ?>;
</script>
What will that output?
var settings = {"settingA":"something","settingB":"something else","wat":9001};
So you can put your required server info in ONE global object (or put it as a property of your application object or something) and can access it.
console.log( settings.settingA ); // returns "something"
Looking further at your question, don't forget you dont' have to stay in the PHP tags. I'm not advocating ever needing PHP in your css, but this should help you grasp the concept:
<style>
<?php foreach ($empresas as $empresa): ?>
.showhide<?php echo $empresa['teaserid'] ?> {
display:none;
}
<?php endforeach; ?>
</style>
In PHP, you can only put variables in double quote strings:
$a = 'Jon';
echo "Hi $a"; // Should output 'Hi Jon'
echo 'Hi $a'; // should output 'Hi $a'
So if you want the Javascript to read:
$(".Jon") // where Jon is the value of $a
Then in PHP you can output it this way:
echo '$(\".' . $a . '\")'; // Notice we are splitting the echo statement into a concatenation of 3 strings
There isn't really a need to have the PHP print out a new block of CSS and Javascript for each item. If you write the css and javascript is a good way, then it will all be handled for you.
One other thing to keep in mind is that PHP is at it's most basic a templating language, so if you find yourself echoing large chunks of code, you are probably being something wrong. Instead something like this:
<?php
$variable = "SOme value";
echo "Some very long huge string with <html> tags and stuff plus $variables";
?>
You can do something like this, opening and closing the tags several times.
<?php $variable = "SOme value"; ?>
Some very long huge string with <html> tags and stuff plus <?php print $variables; ?>
With that covered, here is a reworked version of your code.
As well, rather than needing to make PHP output custom Javascript with hard-coded ids, what you reall need is to structure your javascript so that it doesn't need to know ANY of that stuff at all, as I have done.
<style type='text/css'>
/* The CSS is the same, so just have one class that is used on all the items. */
.empresa-teaser {
width:100%;
background-color: #CCC;
color: #000;
margin-top:10px;
border:1px solid #CCC;
position:relative;
vertical-align:middle;
}
</style>
<script type="text/javascript">
$(function(){
// Hide all of the teasers to start.
$(".empresa-teaser").hide();
// Add a handler for when the show/hide link is clicked.
$(".showhide-empresa-teaser").click(function(){
// When it is clicked, find the next item with the 'empresa-teaser' class
// and show it using a sliding toggle effect.
$(this).nextAll('.empresa-teaser:first').slideToggle(500);
});
});
</script>
<?php foreach ($empresas as $empresa) { ?>
<a href='#' class="showhide-empresa-teaser">
<?php print $empresa['titulo']; ?>
</a>
<br />
<div class="empresa-teaser">TEST</div>
<?php } ?>

Categories