How to preserve c++ template code in html? [duplicate] - javascript

This question already has answers here:
How to display raw HTML code on an HTML page
(30 answers)
Closed 8 years ago.
I'm writing a C++ Style Guide for my company in html/css/javascript. I'm quite irritated with html as it treats anything between < and > as html tag and thus processes them as well. As a result of which my code (which I put in the style guide) doesn't look as such. Here is an example:
<pre>
std::vector<std::string> get_project_names();
template<typename Printable>
void print(Printable const & item);
template<typename FwdIterable, typename Predicate>
FwdIterable find_if(FwdIterable begin, FwdIterable end, Predicate pred);
</pre>
and I want the browser to render it exactly like that, but it doesn't render so, e.g Chrome doesn't show <std::string> part, and IE 8.0 capitalize <std::string> as <STD::STRING> (and all such template codes).
I don't want any kind of interference by html engine. Is there any simple way to achieve what I want? Any polite way to tell the browser to not modify my code?
Note that replacing < with < and > with > would work, but it is cumbersome to write it everytime I write a template code. It also makes my code difficult to read in the source code of the html. So I'm looking for a simple solution.

The notion of a "polite way to to tell the browser to not modify (parse) my code" is precisely what XML's CDATA does. Nothing more, nothing less.
CDATA does not exist in HTML, so there is no way in HTML to treat <std:vector> as anything other than on opening tag for the (non-existent) std:vector element.
The normal way to do this is a server-side transformation. Now if you aren't generating your HTML server-side, and are instead writing it by hand, you can make your life just a dash easier with a client-side transformation like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page Title</title>
<script src="http://coffeescript.org/extras/coffee-script.js"></script>
</head>
<body>
<pre><script type="text/coffeescript" >document.write "
std::vector<std::string> get_project_names();
".replace('<','<')
</script></pre>
</body>
</html>
Here I used CoffeeScript because of its multiline string capability which is coming in ES6 for regular JavaScript. It makes it easy to just drop in your code between the boilerplate lines.
Now I know full well even this solution is lacking! If your inserted code contains a " you're out of luck. And it doesn't escape ampersands.
Bottom line is that there is no CDATA, so no "simple" solution exists. A transformation, client-side or server-side, is required.
Have you tried markdown?

I've been dealing with this particular problem for years, and it's always been frustrating. I've always appreciated the simplicity and elegance of Markdown, so I did a little research to see if there was any way to use Markdown to build an HTML document.
Thing is, code samples sometimes involve HTML, yet HTML is the language we're using to write style guides and API documentation, so my thought was that if we wrote the API documentation and style guides in Markdown, we'd eliminate all of the conflicts between HTML and the syntax of other languages.
I found Strapdown.js, which is a library that allows you to create a Web page with pure Markdown. The library then compiles it to HTML and renders it on the page client side. We put together the API documentation for one of our products using this library, and we published it as a GitHub page.
Here's a small, concise example:
<!DOCTYPE html>
<html>
<title>JavaScript API</title>
<xmp theme="united" style="display:none;">
## Print the name
Print the user's name:
```javascript
function printName(name) {
alert(name);
}
```
</xmp>
<script src="http://strapdownjs.com/v/0.2/strapdown.js"></script>
</html>
Everything inside the <xmp> tags gets compiled to HTML.
Note: The XMP tag has been deprecated for some time as per the Mozilla HTML documentation on XMP. Thus, you may want to either hack the code to make it use PRE or CODE, or you may want to consider using the lower-level Marked library that was used to build Strapdown.js. I filed an issue with the Strapdown.js team.

For that you can use this
<pre>
std::vector<std::string> get_project_names();
template<typename Printable>
void print(Printable const & item);
template<typename FwdIterable, typename Predicate>
FwdIterable find_if(FwdIterable begin, FwdIterable end, Predicate pred);
</pre>
This would be encoded and you'll get the result that you want.
Here is the fiddle for that: http://jsfiddle.net/afzaal_ahmad_zeeshan/7B9xB/
JavaScript code
The JavaScript method of doing this would be simple, you can convert the whole code to a String variable.
As this
var string = "content here";
Then apply this,
string.replace('<','<').replace('>','>');
Convert all the characters and then have then rendered by the Browser.
http://jsfiddle.net/afzaal_ahmad_zeeshan/7B9xB/1/

For my book I used http://markup.su/highlighter/ syntax highlighter. Paste the code into it, generate highlighted code, and paste the latter into the HTML document. Worked pretty well. Here's a fiddle with your code: http://jsfiddle.net/6GTs2/.
Here's your code highlighted for HTML:
<pre style="background:#000;color:#f8f8f8">std::vector<std::string> <span style="color:#89bdff">get_project_names</span>();
<span style="color:#99cf50">template</span><<span style="color:#99cf50">typename</span> Printable>
<span style="color:#99cf50">void</span> <span style="color:#89bdff">print</span>(Printable const & item);
<span style="color:#99cf50">template</span><<span style="color:#99cf50">typename</span> FwdIterable, <span style="color:#99cf50">typename</span> Predicate>
FwdIterable <span style="color:#89bdff">find_if</span>(FwdIterable begin, FwdIterable end, Predicate pred);
</pre>

Related

Pig Latin translator using a While Loop in Javascipt

My son is teaching himself JavaScript. (He’s too young to have an account here.) He’s trying to write a Pig Latin translator using a “while loop.” The basic question he right now is how to sequence the code - so the user types in the word, then the program translates it, then the result appears in the alert box. He’s brand new to this, so if anyone has any friendly feedback it would be much appreciated.
Here’s what he’s got:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="Javascript">
<!-- Beginning of JavaScript -
</SCRIPT>
</HEAD>
<BODY bgcolor="Blue">
<h3> Type some text then click TRANSLATE. </h3>
<FORM>
<INPUT NAME="wordToTranslate" TYPE=Text>
<INPUT NAME="submit" TYPE=Button VALUE="TRANSLATE" onClick="alert(form.wordToTranslate.value)" style="font-size:1em;background:lime">
</FORM>
<script>
while (wordToTranslate.substring(0, 1) = bcdfghjklmnpqrstvwxyz) {
console.log(var wordWithoutFirstLetter = wordToTranslate.slice(0, 1);
var wordWithoutLastLetters = wordToTranslate.slice(1) var wordToTranslate = wordWithoutFirstLetter + wordWithoutLastLetters;
++
wordToTranslate + ay
</script>
Oh my, there are a lot of errors in this code. I would really recommend trying some easier examples first. But to save you some time in the future, here are (some) of the issues I see in your JavaScript. Every one of these will cause an error and stop the code from running.
The primitive strings are not inside quotation marks or apostrophes (for instance, bcdfghjklmnpqrstvwxyz should be "bcdfghjklmnpqrstvwxyz")
Attempting to log syntax rather than a string (or object that can be converted to a string): console.log(var ...) will cause an error
Using an increment (++) operator on a string variable...
some parentheses are missing closing parentheses, and the curly bracket has not closing curly bracket
you never actually get the string to use from the HTML element (i.e., the "value" of the <INPUT>).
After working with some easier examples first and building up to this, I would suggest googling a JavaScript pig latin example and using it as a reference to learn the more complicated concepts (like matching the first letter to a consonant). Good luck!
Since you're looking for general help, I would gently suggest that if he's learning JavaScript and HTML that he learn the newer versions, namely HTML5 , ES6+, and CSS3.
Below is essentially what he has so far--Pig Latin translation code not included--but moved to the newer standards.
'use strict';
const btnTrans = document.getElementById('btnTrans');
const txtWord = document.getElementById('txtWord');
btnTrans.addEventListener('click', translate);
function translate() {
console.log(txtWord.value);
}
body {
background-color: blue;
}
button {
font-size: 1em;
background:lime
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form>
<input name="wordToTranslate" id="txtWord" type="text">
<button type="button" id="btnTrans">Translate</button>
</form>
</body>
<script src="script.js"></script>
</html>
Note the DOCTYPE on the html. Also, all of the HTML elements are lowercase and the attribute values are quoted. JavaScript side, the event listener for the button click event is wired up in the JavaScript code, not in the HTML. The variables are set using const, which is scoped differently than var. I've also moved the inline styles to a CSS file and gotten rid of the old, deprecated ones like bgcolor.
Separating the code into separate files like this creates a clear responsibility for each part of the overall app: the HTML is the view; the CSS styles that view and can be overridden or changed in the future; the JavaScript acts as the controller.
I don't really expect this to be selected as the answer to this question; rather, it's general advice for a general question and new-to-the-web-world programmer. Welcome aboard! =)

parse <script> tag with js/jQuery

I have a HTML page where a user is able to edit a HTML resource (using ACE Editor). Within this HTML source, there is a <script>-tag, which does some pretty basic stuff.
Is there any elegant solution to parse the script tag in order to (e.g.) evaluate the variables used within the script tag? For "normal" tags I use parseHTML() to have the html as a jQuery object.
From this example, I would like to retrieve the value of $myVal (which is "f00") and write it to #myLabel:
<textarea id="myScript" rows="5" readonly>
<script>
$myVal = "f00";
</script>
</textarea>
<label id="myLabel">Hello</label>
$(function(){
$scriptVar = $('#myScript').text;
// parse the $scriptVar
// retrieve the value of, $myVal, write it to #myLabel
//$myParsedValue = ???
//$('#myLabel').text('bar!');
});
And here is the fiddle: https://jsfiddle.net/stepdown/jqcut0sn/
Is this possible at all? I don't really care about vanilla js, jQuery, regex or maybe even an external library for that purpose.
Thanks to #JeremyThille, who pointed me to the right direction. I found out, what I want to achieve is possible through jQuerys $.globalEval() - see the official documentation.
Basically what globalEval() does: it runs the script which is written in the <textarea> and makes the variables / functions globally accessible.
IMPORTANT: this implies, that syntax errors (etc) by the user will break the evaluation, and sequential functionality could be flawed. Also, the new variables are GLOBAL, so basically a user could rewrite scripts on the hosting page. (In my case both problems are of minor importance, since this is an internal application for trained users - they also have syntax highlighting through the amazing ACE editor. But I wanted to make sure to point it out. Also, there are several articles regarding the risks/ouch-moments when using eval()...)
I updated the fiddle to achieve what I wanted: https://jsfiddle.net/stepdown/Lxz7q6uv/
HTML:
<textarea id="myScript" rows="5" readonly>
$myVal = "f00";
</textarea>
<hr />
<label id="myLabel">Hello</label>
Script:
$(function(){
var myScriptContent = $('#myScript').text();
$.globalEval(myScriptContent);
console.log($myVal);
$('#myLabel').text($myVal);
});

Inject html after review widget loads for schema markup

My webstore uses Kudobuzz for product reviews, but our e-commerce platform (PDG) isn't supported for SEO markup data.
This widget does not support schema markup on it's own, so I want to somehow select the relevant pieces and inject the schema markup to the various divs/spans that make up the widget. One problem is figuring out how to inject code that google can parse, and another is figuring out how to make the actual selectors for this super bloated widget.
Here is a codepin of the widget and some markup data that is already on the site: http://codepen.io/anon/pen/GpddpO
Here is a link to a product page if you want to see how everything works: https://www.asseenontvhot10.com/product/2835/Professional-Leather--Vinyl-Repair-Kit
This is (roughly) the markup I'm trying to add if it helps:
<div itemscope itemtype="http://schema.org/Review">
<div itemprop="reviewBody">Blah Blah it works 5 star</div>
<div itemprop="author" itemscope itemtype="http://schema.org/Person">
Written by: <span itemprop="name">Author</span></div>
<div itemprop="itemReviewed" itemscope itemtype="http://schema.org/Thing">
<span itemprop="name">Stop Snore</span></div>
<div><meta itemprop="datePublished" content="2015-10-07">Date published: 10/07/2015</div>
<div itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating">
<meta itemprop="worstRating" content="1"><span itemprop="ratingValue">5</span> / <span itemprop="bestRating">5</span> stars</div>
</div>
Theoretically you could write a very small amount of microdata using css :before and :after - with content but it would need all spaces and symbols converted into ISO format, eg.
#name:before { "\003cspan\2002itemprop\0022name\2033"}
#name:after { content: "\2044\003cspan003e"
even spaces need to be substitued with \2002 or an equivalent whitespace
code
should wrap this microdata to your HTML to any element called name:
<span itemprop="name">...</span>
Clearly this can only work if the widget lets you have clear ids or class names for the elements added, and it may be useless you know the type of object reviewed first (eg Book, Movie, since this needs to go at the start in the example I gave - which is incomplete). The code would need to be nested correctly so if you want further help can you edit your question with example HTML for a completed review.
Writing your own JSON-LD script at the top of the page is another option - it would be a different question (if you get stuck) but isn't embedded within the data itself
Edit
it's a good idea to test the css in a separate environment first, eg setup a jsfiddle

Are they any syntax highlighting plugins that will allow you to embed an ignorable html element into a snippet?

I am trying to make dynamic code examples for our api that can be constructed from from input html elements.
A paired down example looks like this, I give the user an input to name the device they would like to create.
<input class="observable-input" data-key="deviceName" type="text" value="deviceKey" />
I would then like that input to update code examples (replacing the device name in the example with the one the user inputs).
<code lang="python">
device = { "name": "<span data-observeKey="deviceName">Name</span>" }
client.createDevicewrite(device)
</code>
I have all of the code setup for observing a change in the input and updating the code examples, this works great. All of the syntax highlighters I have looked at, usually chop the snippet up and rerender the example wrapped with its own html (for styling). Is there an option/configurable way to get a syntax highlighter to not strip the these tags, or is there a different approach I should be looking at for preserving the syntax highlighting and still supporting dynamic updates without having to do a full text search of each snippet's rendered tags.
The example output of the pygment (current syntax highlighter I'm using).
<li>
<div class="line">
<span class="n">device</span>
<span class="o">=</span>
<span class="n">{</span>
<span class="s">"name"</span>
<span class="p">:</span>
<span class="s">"Name"</span>
<span class="n">}</span>
</div>
</li>
I decided to just go with a brute force approach, it ended up being decently performant, ill leave my code here if anyone is interested in what I did
https://gist.github.com/selecsosi/5d41dae843b9dea4888f
Since i use backbone, lodash, and jquery as my base app frameworks the gist uses those. I have a manager which will push updates from inputs to spans on the page which I use to dynamically update the code examples

Is using custom HTML tags and replacing custom tags with outerHTML okay?

Is it alright to define and use custom tags? (that will not conflict with future html tags) - while replacing/rendering those by changing outerHTML??
I created a demo below and it seems to work fine
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<div id="customtags">
<c-TextField name="Username" ></c-TextField> <br/>
<c-NameField name="name" id="c-NameField"></c-NameField> <br/>
<c-TextArea name="description" ></c-TextArea> <br/>
<blahblah c-t="d"></blahblah>
</div>
</body>
<script>
/* Code below to replace the cspa's with the actual html -- woaah it works well */
function ReplaceCustomTags() {
// cspa is a random term-- doesn;t mean anything really
var grs = $("*");
$.each(grs, function(index, value) {
var tg = value.tagName.toLowerCase();
if(tg.indexOf("c-")==0) {
console.log(index);
console.log(value);
var obj = $(value);
var newhtml;
if(tg=="c-textfield") {
newhtml= '<input type="text" value="'+obj.attr('name')+'"></input>';
} else if(tg=="c-namefield") {
newhtml= '<input type="text" value="FirstName"></input><input type="text" value="LastName"></input>';
} else if(tg=="c-textarea") {
newhtml= '<textarea cols="20" rows="3">Some description from model</textarea>';
}
obj.context.outerHTML = newhtml;
}
z = obj;
});
}
if(typeof(console)=='undefined' || console==null) { console={}; console.log=function(){}}
$(document).ready(ReplaceCustomTags);
</script>
</html>
Update to the question:
Let me explain a bit further on this. Please assume that JavaScript is enabled on the browser - i.e application is not supposed to run without javascript.
I have seen libraries that use custom attributes to define custom behavior in specified tags. For example Angular.js heavily uses custom attributes. (It also has examples on custom-tags). Although my question is not from a technical strategy perspective - I fail to understand why it would strategically cause problems in scalability/maintainability of the code.
Per me code like <ns:contact .....> is more readable than something like <div custom_type="contact" ....> . The only difference is that custom tags are ignored and not rendered, while the div type gets rendered by the browser
Angular.js does show a custom-tag example (pane/tab). In my example above I am using outerHTML to replace these custom tags - whilst I donot see such code in the libraries - Am I doing something shortsighted and wrong by using outerHTML to replace custom-tags?
I can't think of a reason why you'd want to do this.
What would you think if you had to work on a project written by someone else who ignored all common practices and conventions? What would happen if they were no longer at the company to find out why they did something a certain way?
The fact that you have to just go through with JavaScript to make it work at all should be a giant red flag. Unless you have a VERY good reason to, do yourself a favor and use the preexisting tags. Six months from now, are you going to remember why you did things that way?
It may well work, but it's probably not a good idea. Screen readers and search engines may have a hard/impossible time reading your page, since they may not interpret the JavaScript. While I can see the point, it's probably better to use this template to develop with, then "bake" it to HTML before putting it on the server.

Categories