Question

Edit: Editing for clarity and actual use. Actual use might even make this situation easier?

I'm building a style guide and I want to include source code to the common styles/patterns for people who will be using the guide. My plan is to abstract out all the heavy HTML code modules into external files and pull them in using jQuery then use SyntaxHighlighter to highlight what's being presented on the screen. The HTML below shows my intent and what I'd like to do.

I've removed all JavaScript for now since it doesn't add any value to the question at hand. I'll update with anything I come up with.

<div class="sg-section">
    <div class="sg-section-body">
        <div data-load="markup/pagination.html"></div>
    </div>
    <div class="sg-section-code">
        <small>Source Code</small>
        <pre class="brush: js">
            <!-- This is where I want to print out the contents  -->
            <!-- of the 'sg-section body' above and show it's source -->
        </pre>
    </div>
</div>

I can get the data loaded with a simple $('[data-load]'.each(); statement, but I'm having a hard time printing the result out into sg-section-code and getting it hightlighted.

Conclusion: Switched to Prism. Works beautifully.

Was it helpful?

Solution

Edited:

  function loadScript(placeholder){
    var $p = $(placeholder);
    var deferred = $.Deferred();
    $p.load($p.attr('data-load'),function(response){
        $p.parent().append(response).end().remove();   
        deferred.resolve();
    });
    return deferred;
} 

to remove the placeholder and insert your code from external html directly, this should solve your problem that only display the placeholder instead of real code.

your problem is that load is an async method, and you don't know when to call SyntaxHighlight.all();

so, the solution come into my head is use jQuery.Deferred object. let load tell you when it fininsh loading all external scripts.

first extract the method loadScript

function loadScript(placeholder){
  var $p = $(placeholder);
  var deferred = $.Deferred();
  $p.load($p.attr('data-load'),function(){
    deferred.resolve();
  });
  return deferred;
}

then push all the task into an array, finally use $.when().then() to notify when all the script has been loaded, then call SyntaxHighlighter.all();

$(function(){
  var q = [];
  $('[data-load]').each(function(item){
    q.push(loadScript(item));
  });
  $.when.apply($, q).done(function(){
    SyntaxHighlighter.all();
  });
});

OTHER TIPS

$(document).ready(function(){

    // Get Markup Pages
    $("[data-load]").each(function (index) {
        $(this).load($(this).attr("data-load"),function(){SyntaxHighlighter.all()});
    });
});

This should work, as SyntaxHighlighter.all(); is executed after test.html is loaded

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top