How to point to CSS default class using the class attribute - html

Is there a way to point to the default CSS class of an object?
For example, depending if a user is logged in I want to specify a different CSS class to control the style of a header.
$css_class = "";
if($logged_in)
$css_class = "success"
echo "[h1 class=".$css_class."] My Title [/h1]"
If the user is logged in, the css class is set to "success"" otherwise, it's set to "".
I know it's improper w3c to have a blank class, but is there a way that I can just point to the default H1 property instead of creating a separate "not logged in" css class?

An empty class attribute is only invalid under XHTML 1.1. Using a DOCTYPE of XHTML 1.0, HTML 4.01 and HTML 5 is will validate fine.
I wouldn't get too hung up on validation, it's very useful but isn't the be-all and end-all of web development. The only instance where I absolutely make sure my HTML 100% validates is during the very initial HTML and CSS build, since at that stage invalid markup can cause havock with CSS. Once I start adding server-side and Javascript interactions I'm not overly concerned with it.
Of course, you shouldn't just blatently ignore it, but as long as you know what the validation errors are, understand them, and have made a concsious decision not to fix them, I think that's okay.

Why not just omit the class attribute if it's empty?
$css_class = "";
if($logged_in)
$css_class = " class=""success"""
echo "[h1.$css_class.] My Title [/h1]"
(Not sure about the escaping of quotation marks in a string... I have no idea what language you are using...)

It's not invalid to to have an empty string for a className. The class attribute is a cdata-list, so pretty much anything can go in there and it will still validate.
However, you will need to use quotes around your attribute values, otherwise you can't make an empty attribute parse. It's the right thing to do to always include the quotes anyway.
echo '<h1 class="'.htmlspecialchars($css_class).'"> My Title </h1>'

<h1 class="">My Title</h1> will work fine (not sure if it'll pass W3C validation, but it'll work in all major browsers).

$css = $logged_in ? 'success' : 'dummy-undefined-css-value';
echo "<h1 class=\"$css\">My Title</h1>";

If you're going to have a conditional like in Matt Huggins' answer anyway, and considering your comment on Guffa's answer, why don't you move the conditional into the echo? That'll give you the cleanest HTML output. For example:
$css_class = array();
if($logged_in)
{
$css_class[] = "success";
}
if($something_else)
{
$css_class[] = "some-class";
}
echo '<h1' .
empty($css_class)
? ''
: ' class="' . implode(' ', $css_class) . '"'
. '> My Title </h1>';

Related

WordPress generating invalid markup, How to remove it?

Hi I am trying to get the categories associated with a post in it's meta section by using the following code:
<div>FILED AS: <span class="gf-post-meta-result"><?php the_category(' • ') ?></span></div>
WordPress is generating the markup as:
<div>FILED AS: <span class="gf-post-meta-result">Uncategorized</span></div>
The issue:
This part rel="category tag" generated by wordpress is making my code invalid. W3c Validator throws an error saying:
Bad value category tag for attribute rel on element a: The string category is not a registered keyword or absolute URL. Whitespace in path component. Use %20 in place of spaces.
…w all posts in Uncategorized" rel="category tag">Uncategorized</a></span></div>
Any idea how to rectify this?
These two rel values are not invalid. The validator is not up to date.
tag is defined in the HTML5 spec.
category is registered officially.
So it's no problem to use these values. The validator will probably catch up in the future.
Just paste the following code in your functions.php file inside your theme folder
function remove_category_rel($output)
{
$output = str_replace(' rel="category tag"', '', $output);
return $output;
}
add_filter('the_category', 'remove_category_rel');

GWT SafeHtmlBuilder how to insert html code in a div

I don't know if I'm trying to do something against the very nature of SafeHtmlBuilder. The thing is that I'd like to put html code (for instance, an < a > tag) in a div and make it safe. So here is my code:
SafeHtmlBuilder builder = new SafeHtmlBuilder();
builder.append(TEMPLATES.diagramHeader(
BasicConstants.diagramHeaderId + "description",
newBox.getDescription());
newDiv.setInnerHTML(builder.toSafeHtml().asString());
And my template:
#Template("<div id=\"{0}\">{1}</div>") /* Description */
SafeHtml diagramHeader(String idDesc, String description);
When getDescription() returns a string with html code (e.g., an < a > tag) and the contents of newDiv are rendered, I don't see the hyperlink, what I see is the HTML CODE of the hyperlink.
I would like to see the hyperlink, how can I do this? (I am willing to sacrifice HTML's safety for the cause).
Thanks!
If the description argument to the template can contain markup, then it should be of type SafeHtml.
You'd then use SafeHtmlUtils.fromTrustedString(newBox.getDescription()), as you're trusting newBox.getDescription() to be safe.
As a side note, I don't understand why:
you use a SafeHtmlBuilder to append() only once
you use setInnerHTML instead of setInnerSafeHtml (maybe you're not using GWT 2.5?)

How can I parse place holder text in a HTML file which are then replaced with custom tags?

First a bit of background information. I create HTML emails at my work place and the whole process is very tedious. It goes a little little like this...
Code markup for HTML using tables and some CSS
Parse HTML and CSS using Premailer so all CSS is inline
Test HTML works in all email clients
Create a copy of the inline version of HTML and start adding in proprietary variables to email tool used for sending emails, ie <%=constant.first_name%>, <%=unsubscribe_link%>
Test in email client to see if it works and client is happy. If not repeat steps 1 through 5 again.
So as you can see it gets really tedious after a while.
What I would like to do is create a command line script similar to Premailer which allows me to parse a HTML file with variables stored in it without destroying the example text already in the HTML. That way when you are previewing the HTML it all looks dandy.
For example...
Store the first name function as a variable for own use.
$first_name = "<%=constant.first_name%>
Then tell the parser what word(s) to replace with the appropriate variable.
<p>My name is <!-- $first_name -->Gavin<!-- /$first_name --></p>
So that the final output looks something like:
<p>My name is <%=constat.first_name%></p>
Would such a thing be possible? Is there a better syntax I could, a custom tag like <first_name>Gavin</first_name>, if the browser can handle it.
Any advice is helpful. :)
I've seen this done before using a syntax like:
{assign_variable:first_name="Jesse"}
Then, you could use it like:
{first_name}
The way you'd parse this (provided you're using PHP) would be something like:
<?php
// Our Template Code
$strHTML = <<<EOT
{assign_variable:first_name="Jesse"}
{assign_variable:last_name="Bunch"}
Hello, {first_name}!
EOT;
// Get all the variables
$arrMatches = array();
preg_match_all('/\{assign\_variable\:([a-zA-Z\_\-]*)\=\"([a-zA-Z0-9]+)\"\}/', $strHTML, $arrMatches);
// Remove the assign_variable tags
$strHTML = preg_replace('/\{assign\_variable\:([a-zA-Z\_\-]*)\=\"([a-zA-Z0-9]+)\"\}/', '', $strHTML);
// Combine them into key/values
$arrVariables = array_combine($arrMatches[1], $arrMatches[2]);
foreach($arrVariables as $key=>$value) {
// Replace the variable occurrences
$strHTML = str_replace('{' . $key . '}', $value, $strHTML);
}
// Send the parsed template
echo $strHTML;
Which outputs:
Hello, Jesse!
Note, this is a very basic example. Here are some improvements to make on this code before using it in production:
Edit the regex to allow the right characters.
Maybe implement a better replacement method than a loop
Check for parse errors
Benchmark performance
All in all, I think you get the idea. Hope this points you in the right direction.
I have a similar situation
I have created a "format template" like this:
<?php // section1 $var1/$var2 ?>
<head>
<title>$var1</title>
<meta name="description" content="$var2">
</head>
<?php // section2 $var1/$var2 ?>
<body>
hello: <p>$var1</p>
news for you: <p>$var2</p>
</body>
it is valid php code and valid html code, so you can edit it with dreamwaver or similar, and you can host it also.
then a php script replaces all ocurrences of vars in all sections.

HTML Single Line Text, appended with "..." if longer than one line?

Does HTML support a behavior of text rendering where multiple lines will be avoided with an automatic placement of "..." ? Sorry, I just cannot find the style/tag associated with this behavior, if it exists!
No, there is nothing built in.
You need to either do it yourself serverside, or write some JavaScript that will count lines and replace the rest of the line with an ellipsis (...).
There is a text-overflow-mode defined in the CSS3 spec that will do this, but as a working draft it is not final and will not necessarily work on current browsers.
The property you're looking for is the CSS text-overflow: ellipses. Unfortunately it does not work in Firefox. Here is a resource on it:
http://www.css3.info/preview/text-overflow/
You can kind of hack it in Firefox, with e.g.
http://www.jide.fr/english/emulate-text-overflowellipsis-in-firefox-with-css
But the only real cross-browser solution would be a JavaScript one, like this maybe, or perhaps one of the ones in the comments on this page:
http://ajaxian.com/archives/ellipsis-or-%E2%80%9Ctruncate-with-dots%E2%80%9D-via-javascript
Short answer: No.
Longer answer: This is possible if you're using a programming backend (e.g. PHP) that outputs HTML to the front end. You could do something like
<?php
if(str_len($yourText) > 100) {
echo substr($yourText, 0, 100) . "...";
}
?>

Prevent CKEditor from formatting code in source mode

How can you prevent any automatic formatting when in CKEditor when viewing in source mode?
I like to edit HTML source code directly instead of using the WYSIWYG interface, but whenever I write new lines, or layout tags how I would indent them, it all gets formatted when I switch to WYSIWYG mode and then back to source mode again.
I stumbled upon a CKEditor dev ticket, Preserve formatting of ProtectedSource elements, that alluded to a setting which may have existed once upon a time which would be exactly what I'm after. I just want to know how I can completely turn off all automatic formatting when editing in source mode.
I came up with a solution I thought would be foolproof (albeit not a pleasant one).
I learned about the protectedSource setting, so I thought, well maybe I can just use that and create an HTML comment tag before all my HTML and another after it and then push a regular expression finding the comment tags into the protectedSource array, but even that (believe it or not) doesn't work.
I've tried my expression straight up in the browser outside of CKEditor and it is working, but CKEditor doesn't protect the code as expected (which I suspect is a bug involving comment tags, since I can get it to work with other strings). In case you are wondering, this is what I had hoped would work as a work-around, but doesn't:
config.protectedSource.push( /<!-- src -->[\s\S]*<!-- end src-->/gi );
and what I planned on doing (for what appears to be the lack of a setting to disable formatting in source mode) was to nest all my HTML within the commented tags like this:
<!-- src -->
<div>some code that shouldn't be messed with (but is)</div>
<!-- end src -->
I'd love to hear if anyone has any suggestions for this scenario, or knows of a setting which I have described, or even if someone can just fill me in as to why I can't get protectedSource to work properly with two comment tags.
I really think it's gotta be a bug because I can get so many other expressions to work fine, and I can even protect HTML within the area of a single comment tag, but I simply cannot get HTML within two different comment tags to stay untouched.
My solution to this was to use comments in my system, but before feeding the page content to CKEditor, convert them to custom HTML tags. Then, upon save, convert them back to my comment tags.
For your syntax that would be something like this in PHP. Before printing the page content to the textarea:
$content = str_replace(array('<!-- src -->','<!-- end src -->'),array('<protected>','</protected>'),$content);
Before saving the resulting content:
$content = str_replace(array('<protected>','</protected>'),array('<!-- src -->','<!-- end src -->'),$content);
In the CKEditor configuration:
protectedSource:[/<protected>[\s\S]*<\/protected>/g]
Hope that helps!
I wanted to preserve newlines in my source, and the protectedSource feature works well for that. I added this to my config.js:
config.protectedSource = [/\r|\n/g];
config.allowedContent=true; will do the trick
Here is the full HTML code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CKEditor</title>
<script src="http://cdn.ckeditor.com/4.5.10/standard/ckeditor.js"></script>
</head>
<body>
<textarea name="editor1"></textarea>
<script>
CKEDITOR.config.allowedContent=true;
CKEDITOR.replace( 'editor1' );
</script>
</body>
</html>
I solved this problem by simply surrounding the back-end output of edit form page with a conditional on a $_GET variable - when you click on "Expert Mode" it loads a plain textarea instead of the ckeditor system. Your invocation of the ckeditor object will vary depending on your setup. ( I have a custom class that calls/builds the editor object )
<div id="postdivrich" class="postarea">
<?php
if( isset( $_GET['expert'] ) )
{
print "<div style=\"text-align:right;\">Editor mode</div>\n";
print "<textarea name=\"content\" style=\"height:400px;width:{$nEwidth}px;\">{$aDoc['content']}</textarea>\n";
}
else
{
print "<div style=\"text-align:right;\">Expert mode</div>\n";
require_once( 'admin/editor.class.php' );
$aDoc['content'] = str_replace( "\r", '', str_replace( "\n", '', nl2br( $aDoc['content'] ) ) );
$oEditor = new setEditor( $aDoc['content'], $nEwidth, "400", 'content' );
$oEditor->ShowEditor();
}
?>
</div>
Does this answer help? Basically you can turn off the options adding a javascript, it looks like.