Use Handlebars.js with Web Forms - javascript

I need to figure out how to display JSON data from an ASPHX file into an
ASPX file without using C#. My theory is that I am not able to run the JavaScript because of the order of loading. Using web forms, how can I use a handlebars template inside of an ASP control content placeholder? The below code does not return any HTML to the page.
============= ASP CODE / HTML =============
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="unprocessed.aspx.cs" MasterPageFile="~/Default.Master" Inherits="SurplusApp.unprocessed" %>
<asp:content ContentPlaceHolderID="mainContent" runat="server">
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>
</asp:content>
=============== JS CODE =================
var source = $("#entry-template").html();
var template = Handlebars.compile(source);
var context = { title: "My New Post", body: "This is my first post!" };
var html = template(context);
Update #1:
What I have discovered is that when using web form pages the content placeholder tag does not support the script tag <script id="entry-template" type="text/x-handlebars-template"> however, you can add the template code in your js file and render the template in your web dev console. An example of this can be found on the handlebars github page: https://github.com/wycats/handlebars.js/

Add a MIME type to your web.config file because a web forms page ASPX file with <asp:content></asp:content> does not support adding <script id="entry-template" type="text/x-handlebars-template">
Create a Handlebars template file.
Create a div with a unique id which we will use later to insert our Handbars rendered template.
On the bottom of your ASPX page add a script tag and add two AJAX handlers, one to return the data from a JSON feed and another to return a handlebars template. In our second AJAX call, this is where we will append our newly created HTML from Handlebars.
var responseObject;
$.get('jsonFeed.ashx', function(response){ responseObject = response });
$.get('handlebarsTemplate.hbs', function(response){
var template = Handlebars.compile(response);
var handlebarTemplateInsert = template(responseObject);
$('#element').append(handlebarTemplateInsert);
});

Related

Re-using components with handlebars.js

I am trying to create reusable components for the different webpages of my website. I started using handlebars.js and I have the code below right now, I am able to pass simple HTML code with it and display it on the webpage. But I would like to have a whole navbar component rendered instead, and preferably linked to from another html or handlebar file somehow. any ideas?
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.6/handlebars.js"></script>
</head>
<body>
<script id="template" type="template/handlebars">
<h1> my website </h1>
{{>navigationBar}}
</script>
<script>
var partialSrc = "some link to navbar";
Handlebars.registerPartial("navigationBar",partialSrc);
var templateSrc = document.getElementById("template").innerHTML;
var template = Handlebars.compile(templateSrc);
document.body.innerHTML += template();
</script>
</body>
What do you think about writing the template as string in a variable in an external JS-file and load it separate?
template.js
var templateSrc = '<h1> my website </h1>\
{{>navigationBar}}';
index.html
<body>
<script src="template.js"></script>
<script type="text/javascript">
var partialSrc = "some link to navbar";
Handlebars.registerPartial("navigationBar",partialSrc);
let template = Handlebars.compile(templateSrc);
document.body.innerHTML += template();
</script>
</body>
This is a simplified presentation. Ofcourse you have to make sure, that template.js is loaded before compiling with handlebars.
How do I include a JavaScript file in another JavaScript file?

Why my custom js in bundle doesn't show up in custom view MVC5

I want to exract some js file and call it only in one view, separetely from my bundles which is called from _LandingLayout.cshtml template page.
In my BundleConfig.cs I have
bundles.Add(new ScriptBundle("~/scripts/app/index").Include(
"~/Scripts/App/home.js",
"~/Scripts/App/location.js"
));
and my view like this:
#{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/_LandingLayout.cshtml";
}
<!-- Main Content -->
...some html markup
<!-- End of Main Content -->
#Scripts.Render("~/scripts/app/index")
every css and js file from _LandingLayout.cshtml is shows correctly, if I put "~/scripts/app/index" into _LandingLayout.cshtml, it shows correctly.
But if I want to render it separately from my _LandingLayout.cshtml it enters into js file home.js and yellows whole the file like a debugger (I didn't put any debugger into my home.js) and when I enter F10, I get an error:
0x800a1391 - JavaScript runtime error: '$' is undefined
I have searched for this error and I find this
But, I have referenced jQuery lib.
Only that cross my mind, that maybe engine renders first my line of code:
#Scripts.Render("~/scripts/app/index")
and later on renders all bundles from _LandingLayout.cshtml page?
you need to add you new section in _LandingLayout.cshtml view after all js files referenced inside it.
for example we will add section named "ExtraJs" after jquery reference as following:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
#RenderSection("ExtraJs", false)
then inside your view you can reference this section as following
#{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/_LandingLayout.cshtml";
}
<!-- Main Content -->
...some html markup
<!-- End of Main Content -->
#section ExtraJs
{
#Scripts.Render("~/scripts/app/index")
}

HTML Views (UserControl) for Knockout.js

In a single page application, how to use Knockout.js effectively to achieve MVVM. Is there a way to create views (Html files) and viewmodels (javascript files) separately? That can be referred in another HTML master file.
I tried iframe, but it allows user to navigate to individual views. Is there any other way?
Thanks in advance.
Yes, I think this is possible. If you create each view as a template in a separate html file and then load and append the appropriate template to the documents body when you instantiate you viewmodel.
in pseudo-code you'd get something like:
<!-- your page -->
<div id="bindModelHere">
<!-- ko template: loadedTemplate -->
<!-- /ko -->
</div>
<script type="text/javascript">
$(document).ready(function () {
var viewModel = new yourViewModel();
ko.applyBindings(viewModel, document.getElementById('bindModelHere'));
});
</script>
//your javascript
function yourViewModel (){
this.loadedTemplate = ko.observable();
//Load template from server with a get and append to document body
//when loaded and appended do: loadedTemplate("idForTemplate");
}
<!-- the template/view in a separate file-->
<script type="text/html" id="idForTemplate">
<!-- your html -->
</script>
this way you could load your views/templates using ajax and just load the view you'd need.

How do I get and print an .hbs or .handlebars template?

Does anyone know how I can print an .hbs/.handlebars template in an HTML page? I've looked everywhere but I cannot figure out how to put the .hbs files in a directory and then print them in my index.html. Sorry for the question, but I am a new user of handlebars. Thanks in advance!
Let's say you have a handlebars template post.handlebars:
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
Use handlebars precompiler to compile your templates:
$ handlebars post.handlebars -f templates.js
Include the compiled templates and handlebars runtime in your html doc
<script src="/libs/handlebars.runtime.js"></script>
<script src="templates.js"></script>
Now the compiled template will be accessible as a property of Handlebars.templates. Next pass data to the template, generate some html and append it to the DOM.
<script type="text/javascript">
var template = Handlebars.templates.post;
var context = {title: "My New Post", body: "This is my first post!"};
var html = template(context);

 $(document).append(html);
</script>
See http://handlebarsjs.com/precompilation.html for details on precompile. Also there is a great handlebars tutorial here: http://javascriptissexy.com/handlebars-js-tutorial-learn-everything-about-handlebars-js-javascript-templating/
Save your hbs file as a fragment file. Say myTemplate.jspf
Include this in your HTML/JSP file as below
<script type="text/x-handlebars-template">
<%# include file="myTemplate.jspf" %>
</script>

WYSIWYG editor in asp.net page error

I am using an open source wysiwyg editor on one of my asp.net web pages to create news pages... On one page It is put into place like this:
Registered at top of asp.net web page...
<%# Register Src="~/WebUserControls/HTMLEditorControl.ascx" TagName="HTMLEditorControl" TagPrefix="uc2" %>
Incorporated into the page:
<div>
<uc2:HTMLEditorControl ID="HelpTextBox" runat="server" />
</div>
In the code behind there is a Save method that basically saves the above editor data using the id:
dataset.column = htmlTextArea.GetHTML ;
When I try to bring up the page with the editor, I get the error: 'WYSIWYG' is undefined at Line 900, which is:
<script language="javascript" type="text/javascript" >
WYSIWYG.attach('ctl00_ContentPlaceHolder_HelpTextBox_htmlTextArea');
</script>
What's confusing, I have another page set up identically, that produces the same WYSIWYG.attach source, but it handles it with no problem at all. The only difference is the names of the pages. The page that works produces the following, with no problem:
<script language="javascript" type="text/javascript" >
WYSIWYG.attach('ctl00_ContentPlaceHolder_htmlTextArea_htmlTextArea');
</script>
So I'm at a loss...
Does the name of your code-behind class match the class name of your aspx page? Does the aspx page point to the correct code behind file?
My guess is that you copied and pasted but forgot to change that.

Categories