Giter Site home page Giter Site logo

razorclienttemplates's Introduction

Razor Client Templates

The Razor Client Templates library allows you to reuse your Partial Razor Views as client side (JavaScript) templates. In addition to ensuring consistency between the HTML generated on the client with what's generated server-side, it also means that you don't have to maintain two different sets of markup - just write once and run anywhere!

Installation

Install via NuGet!

PM> Install-Package RazorClientTemplates

Usage

It's easy to get started using Razor templates on the client-side. Just follow a few simple steps:

Step 1: Create your Razor template

First, you'll need a Razor template that you're using as a partial view. In fact, you've probably already completed this step.

For example, take the following server-side Razor view:

<div id="movies">
	@foreach(var movie in Model) {
		@Html.Partial("Movie", movie")
	}
</div>

...which uses the Partial view Movie.cshtml:

<div class="movie">	    
    <h2>@Model.Title</h2>	    
    <p>Release Date: @Model.ReleaseDate</p>
    <p>Running Time: @Model.RunningTime</p>
    
    <h3>Actors</h3>
    <ul class="actors">
    @foreach(var actor in Model.Actors) {
        <li>@actor.Name</li>
    }
    </ul>
</div>

Step 2: Convert Razor markup to a Client Template

A client template is actually nothing more than a JavaScript function that produces rendered markup. There are two ways to convert your Razor markup to a JavaScript client template function: render the function inline, or include it as an external JavaScript include.

Inline JavaScript function

You can use the Html.ClientTemplate helper method to render the script inline, directly to your page, like so:

var movieTemplate = @Html.ClientTemplate("Movie")

...which will render the following to the client:

var movieTemplate = function(Model) {
    var _buf = [];
    _buf.push('<div class=\"movie\">	    \r\n	    <h2>');
    _buf.push(Model.Title);
    _buf.push('</h2>	    \r\n        <p>Release Date: ');
    _buf.push(Model.ReleaseDate);
    _buf.push('</p>\r\n        <p>Running Time: ');
    _buf.push(Model.RunningTime);
    _buf.push('</p>\r\n	    \r\n	    <h3>Actors</h3>\r\n	    <ul class=\"actors\">\r\n');
    for (var __i = 0; __i < Model.Actors.length; __i++) {
        var actor = Model.Actors[__i];
        _buf.push('	        <li>');
        _buf.push(actor.Name);
        _buf.push('</li>\r\n');
    }
    _buf.push('	    </ul>\r\n	</div>');
    return _buf.join('');
};

External JavaScript Include

Or, you can use the custom script handler to generate the same code as above, but as an external script include to keep that JavaScript out of your HTML:

<script type="text/javascript" src="@Url.ClientTemplate("Movie", functionName: "movieTemplate")"></script>

Step 3: Use the client template in the browser!

However you get it to the browser, you've now got a JavaScript function that you can call to render markup on the client! Just call the function and pass it a model and it will spit out rendered HTML that you can use however you like:

var renderedMovie = movieTemplate({ 
        Title: "The Big Lebowski",
        ReleaseDate: "1998",
        RunningTime: "117 mins",
        Actors: [ 
            { Name: "Jeff Bridges" },
            { Name: "John Goodman" },
            { Name: "Steve Buscemi" }
        ]
    });

$('#movies').append(renderedMovie);

Supported Scenarios / Known Limitations

Look, in addition to the fact that this project is quite young, Razor markup wasn't designed to be converted into JavaScript functions, so naturally there are going to be some things that work, some things that don't work quite right (yet) and some things that may never work correctly. You are, after all, translating from a statically-typed language to a dynamically-typed language - some things are simply going to be lost in translation!

That being said, here is what is known to be working, not working, and things we plan to get working.

What works:

  • Basic C# code constructs (if/then, foreach, etc.)
  • Basic model property accessors work fine, but of course you are not going to have access to .NET methods and properties on the client (nor will you have JavaScript nuances on the server)
  • Basic foreach loops work, as long as you stick to the basic model property accessors (e.g. foreach(var movie in Model.Movies))
  • Basic if/else checks work against simple boolean properties
  • Comments are "supported" (in that they are ignored...)

Planned to work:

  • Support for Razor Helpers (the @helper MyFunc() syntax) should work soon

What doesn't (and probably never will) work:

  • VB. C# rocks way too much to worry about VB support.
  • JavaScript methods and properties on the server (this should be a given... right? this tool converts from server code to client code, not the other way around!)
  • .NET methods and properties on the client -- stick to basic DTO models!
  • ... You tell us! If you find something that you think should work but doesn't, please submit an issue via our GitHub Issues page!

razorclienttemplates's People

Contributors

jchadwick avatar

Stargazers

 avatar  avatar Tito avatar y、 avatar Maanrouf avatar Mike Weisz avatar Tony Hicks avatar Chris Smith avatar Fred Daley avatar Carlos Alberto Costa Beppler avatar Arash Motamedi avatar hoangitk avatar Brandon G avatar Hugo Nogueira avatar Angus H. avatar Stefan Ortgies avatar lcomplete avatar Victor Foster avatar Edgar Schnüriger avatar  avatar Seth Valdetero avatar Daniel Gonçalves avatar  avatar orhan avatar أشرف صبري avatar Carlos Rodriguez avatar valery sntx avatar Shaun Cruz avatar Jon Parsons avatar Stefan Schälle avatar Oliver Lassen avatar Ruslan Konviser avatar Xu avatar Chris Meagher avatar Zoltan Kochan avatar Christophe Chevalier avatar Alex Shkor avatar Jonah Goldsaito avatar  avatar Garrett Wolf avatar Gorbach Oleksii avatar Vaibhav avatar Søren Bramer Schmidt avatar  avatar Nathan Brown avatar Marcus McConnell avatar Vasili Puchko avatar Thomas Freudenberg avatar Josh Charles avatar Scott Hanselman avatar

Watchers

Marcus McConnell avatar Victor Foster avatar Dean avatar skylark avatar

razorclienttemplates's Issues

Does not load with Razor 3

Get the following error:

Could not load type 'System.Web.Razor.Parser.SyntaxTree.TransitionSpan' from assembly 'System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.