-1

It seems displaying code on the web involves:

  • Encoding HTML entities
  • Formatting

A most basic workflow would thus seemingly be:

  1. Have a code snippet such as:

    <html> I'm a full page html snippet <html>.

  2. Encode it (using one of the many sites found by google) to e.g.:

    &#x3C;html&#x3E; I'm a full page html snippet &#x3C;/html&#x3E;

  3. Add it to the pages html such as follows:

    <code><pre> &#x3C;html&#x3E; I'm a full page html snippet &#x3C;/html&#x3E; </pre></code>


While this works, it is extremely manual, and loses WYSIWYG for me the author when I'm writing code snippets.

(EDITED for clarity:)

What I would simply like is something like this:

<body>
  <encodedhtml (src="")>
     I come from somewhere sensible: Inline or a seperate file. All my <, >, ", ', chars are displayed. I am raw html. 
  <encodedhtml>  
</body>

Additional notes:

  • I think ERB would work, but I'm using Node & Angular - I'd rather not.
  • Jade is far to much of a deviation from normal html for my purposes (to heavyweight), I can't find a node templating engine that isn't. Also have to be careful angular and a templating engine syntax wouldn't clash (as with Handlebars).
  • I could use angular/javascript to pull in the snippets with ajax from the server side, and inject them in the DOM but this just seems wrong. Am I wrong?
  • This post sort of half explains why javascript without ajax is not going to work.
  • I hear rumours of using <script> or <textarea> tags, but I also read you can't syntax highlight a textarea tag. Could I put it in the HTML, hide it, then get it's content with javascript and re-display it? Is that too messy? I can't find examples.
  • Highlightjs and Code-Prettify both take encoded HTML: This seems to be the pattern with syntax highlighters for fundemental reasons.
Dan
  • 2,830
  • 19
  • 37
  • 1
    There are numerous scripts already available for this, no need to do manually. Let google be your friend – charlietfl May 09 '15 at 16:30
  • It was 90 minutes of failed web searching that led me to ask... I'm missing something. Also, the question was all about "how do I not do this manually". – Dan May 09 '15 at 16:51
  • search for `javascript syntax highlighter` or `javascript code editor`, depending on what use you want. Shouldn't have problems finding lots of results – charlietfl May 09 '15 at 16:57
  • Perhaps the question is not clear. It is about implementing a workflow which will allow me to display code snippets like so many websites do, with a separation of input, encoding, and display concerns. I don't need highlighting or an editor, I just want to display escaped html/css/python/ruby/javascript in a body of text. Generally it cannot be put in the HTML document itself if it hasn't been encoded, so I want to store it seperately, and let a script encode it for me. – Dan May 09 '15 at 17:11
  • But that's exactly what syntax highlighter scripts do...just pass in the raw code – charlietfl May 09 '15 at 17:12
  • (And I wonder how people normally do this) – Dan May 09 '15 at 17:12
  • Can put any code you want as text in a script tag that has an unconventional `type` , put in textarea, code tag ...not hard to get the code in a page unescaped. if use a syntax highlighter just tell it what langauge you are using and follow it's docs on set up – charlietfl May 09 '15 at 17:18
  • Could you provide a working example of escaping text (without encoding it using entities)? Nothing you've said has helped me find a solution. Neither highlightjs nor code-prettifier appear to encode html entities as you implied. – Dan May 09 '15 at 18:17
  • why are you using htmlentities in the first place? Here's a simple textarae for example http://jsfiddle.net/do7u8xc2/1 – charlietfl May 09 '15 at 18:21
  • and if you pass the code from json to a syntax script will totally be assured of no issues – charlietfl May 09 '15 at 18:24
  • The question is about displaying text, textarea is an input field. I'm using htmlentities because of http://stackoverflow.com/questions/2820453/display-html-code-in-html – Dan May 09 '15 at 18:56
  • The point of the textarea example is merely to put the code in the page. Then you would transform it with a highlight script. That textarea would never be seen by user. That's an old post , numerous other techniques are common now such as script tags – charlietfl May 09 '15 at 18:58

2 Answers2

1

What about this?

<!-- html -->
<div ng-app="app">
  <div ng-controller="mainController">
    <pre>{{code}}</pre> <!-- outputs: <div>Hello world</div> -->
  </div> 
</div>

 

// js (angular)
angular.module('app', []);

function mainController ($scope) { 
  $scope.code = '<div>Hello world</div>';
}

angular
  .module('app')
  .controller('mainController', mainController);

update using angular's $http (ajax)

$http.get("http://www.reddit.com/r/pics/.json?")
  .success(function (result) {
    $scope.code = result
  })
azium
  • 20,056
  • 7
  • 57
  • 79
  • Much appreciated. I wouldn't want to do html as a string inside js so I'd extend that example to use AJAX and pull in those 'strings' of html from a seperate file. I'm hesitant about doing so. Should I be? - also I've updated the question. Thanks again. – Dan May 10 '15 at 00:16
  • What are you hesitant about? That sounds completely reasonable, just use `$http` to populate your `$scope` variable. It sounds like you're already using Angular so I'm completely confused by your confusion. – azium May 10 '15 at 00:21
  • Just read your update. You're getting bogged down in implementation details. Jade has nothing to do with your problem and ajax is pretty much the standard way of doing everything on the web for the last 10 years. Unless the output of my solution is not what you're looking for, Angular is all you need, and nothing else. – azium May 10 '15 at 00:26
  • Thanks so much. I'm actually learning angular, and I wanted to put my notes down in site form including snippets. i.e. writing a retrospective tutorial as I learn. I expected this to be so easy, it tripped me up because it just wasn't what I was expecting. All of this just before diving into the ajax part of the course I'm doing @@. Now I know. Last question though... won't 50 snippets mean 50 requests in this case (without storing the snippets in json which I don't want to do?). Thanks again. – Dan May 10 '15 at 00:41
  • Updated my answer to include a dead simple ajax request. I'm getting json because I chose a random thing to pull, but it can be html files no problem. And what is 50 a lot to you? I write apps that make thousands of requests per minute (not second) in some cases, and they're surviving still. Unless you're serving your application from a potato you'll be fine. – azium May 10 '15 at 00:44
  • 1
    Also, you can consolidate your snippets into one file and break them up after your first request or use caching. All I'm saying is that there are many non-complex ways to solve your problem. – azium May 10 '15 at 00:49
  • 1
    I come from a testing background - too many performance testers for friends! Awesome. Just awesome, you got me back on track :). – Dan May 10 '15 at 00:51
0

I was asking myself the same question. I had the problem of several snippet codes that where part of html page. It looked totally horrible and difficult to maintain.

I needed to inject code snippets of CSS, HTML and JS. But also have code highlighting to make the code more pleasant to read and understand.

The example implementation is at the elevatezoom-plus demo/examples page

So my solution/explanation is basically to inject async the resources as shown below. The highlighting is done via Prism. The snippets are all expected to be under /snippets directory.
i.e.:

  • /snippets/code-ezp-e03f.html
  • /snippets/code-ezp-e03f.css
  • /snippets/code-ezp-e03f.js
  • etc

HTML (with id's)

<script type="text/javascript" src="https://cdn.rawgit.com/igorlino/snippet-helper/1.0.1/src/snippet-helper.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.rawgit.com/igorlino/elevatezoom-plus/1.1.8/demo/css/prism.css"/>
<script type="text/javascript" src="https://cdn.rawgit.com/igorlino/elevatezoom-plus/1.1.8/demo/js/prism.js"></script>

<h6>HTML</h6>
<pre><code id="code-ezp-e03f-html"></code></pre>
<h6>JAVASCRIPT</h6>
<pre><code id="code-ezp-e03f-js"></code></pre>
<h6>CSS</h6>
<pre><code id="code-ezp-e03f-css"></code></pre>

FRAMEWORK JS (snippet-helper.js)

var snippetHelper = {};
(function () {
    snippetHelper.loadSnippet = function (filename, ext) {
        jQuery.get('snippets/' + filename + '.' + ext, function (data) {
            var element = $('#' + filename + '-' + ext);
            if (ext === 'html') {
                element.addClass('language-markup');
            }
            if (ext === 'js') {
                element.addClass('language-javascript');
            }
            if (ext === 'css') {
                element.addClass('language-css');
            }
            element.text(data);
            if (Prism) {
                Prism.highlightAll();
            }
        });
    }
    snippetHelper.loadSnippets = function (snippets) {
        $.each(snippets, function (idx, snippet) {
            $.each(snippet.ext.toLowerCase().split(','), function (idx, ext) {
                snippetHelper.loadSnippet(snippet.code, ext)
            });
        });
    }
}());

REGULAR JS (non angular-variant)

<script type="text/javascript">
    var snippets = [
        {code: "code-ezp-e01", ext: "html,js"},
        {code: "code-ezp-e02", ext: "html,js"},
        {code: "code-ezp-e03f", ext: "html,js,css"},
        {code: "code-ezp-e12", ext: "html,js"}
    ];
    $(document).ready(function () {
        snippetHelper.loadSnippets(snippets);
    });
</script>

ANGULAR (for your scenario)

var app = angular.module('yourapp', ['somedependency']);
app.run(function() {
var snippets = [
            {code: "code-ezp-e01", ext: "html,js"},
            {code: "code-ezp-e02", ext: "html,js"},
            {code: "code-ezp-e03f", ext: "html,js,css"},
            {code: "code-ezp-e12", ext: "html,js"}
        ];
        $(document).ready(function () {
            snippetHelper.loadSnippets(snippets);
        });
});

The framework JS I have put under a free open source project snippet-helper (disclaimer: I'm the author)

(disclaimer 2: I'm the maintainer of the free open source project elevatezoom-plus )

Igor Lino
  • 532
  • 7
  • 10