There are so many template engines for node.js and express and there is even this detailed comparison: http://paularmstrong.github.com/node-templates/index.html This led me to check out EJS, Mu2 and JQTpl and I spent some hours on experimenting which of them fits my needs best.
I know that there already are several questions concerning which framework is best, but none of them concentrates on the possibility of using helpers. I tried to build a form helper (which should render input tags and their values if I pass an object into it) together with all of them but I did not find a straight forward way accomplishing it.
Are there any recommendable modules that enable me to use helpers? Maybe even using mustache.js (which - for me - feels like the best of the ones I tried)? Thanks in advance!
I can't point you to the comparison you are looking for, but nearly all the templating engines I've looked at have had a facility for helpers.
If you are using Express (which you mentioned in your question), you can tell Express what helpers you want to expose to whatever template engine you are using (set via the "view engine" app variable) - see the following sections of the Express Guide for details:
View Rendering - explains how to configure Express to use a particular templating engine. The example refers to Jade, which is installed with Express by default, and does support helpers.
Server.helpers() - How to register static view helpers to be passed to your template
Server.dynamicHelpers() How to register helpers which can access the Request and Response objects
Some template engines come with support for Express built in, although they may require an extra configuration step. I am partial to CoffeeKup (and the more updated fork coffeecup), which lets you write your views in Coffeescript; enabling auto-compilation requires and extra call to the Express server object (and covered in the docs):
app.register('.coffee', coffeecup.adapters.express);
Others may offer an additional node package, you may find npm search express- instructive. For example, express-handlebars specifically fixes up app.helpers() and app.dynamicHelpers() to work with handlebars. (Disclaimer: I haven't used this module personally).
Related
I am quite new to Mediawiki and am trying to get templates work.
I managed to get a simple one working but the templates are shown in a weird way but no error is provided.
I looked at your template:
http://wordpress-251650-782015.cloudwaysapps.com/index.php?title=Template:Cita_conferenza
And it invokes a LUA module:
http://wordpress-251650-782015.cloudwaysapps.com/wiki/Modulo:Citazione
You can read more information about using this module on
https://it.wikipedia.org/wiki/Modulo:Citazione
#Revious
A bit late, but you may still be interested...
If you want to copy a template from Wikipedia, but it is using lua modules, you can look in the history tab to find pre-lua versions that use only wikicode (lua has been implemented in 2013 in Wikipedia, but some templates have been given modules later).
Here, it seems to be this version
Be careful, however, if the template you are copying uses subtemplates (this does not seem to be the case here).
If this is the case, you should either make copies of the templates with the same name and code, or add their code to the main template, paying attention to the parameter names which will need to be adapted.
Good luck.
Note: this is not a dupe of this or this other question. Read on: this question is specific to the Code-Sharing template.
I am doing some pretty basic experiments with NativeScript, Angular and the code sharing templates (see: #nativescript/schematics).
Now I am doing some exploration / poc work on how different "build configuration" are supported by the framework. To be clear, I am searching for a simple -and hopefully official- way to have the application use a different version of a specific file (let's call it configuration.ts) based on the current platform (web/ios/android) and environment (development/production/staging?).
Doing the first part is obviously trivial - after all that is the prime purpose of the code sharing schematics. So, different versions of the same file are identified by different extensions. This page explain things pretty simply.
What I don't get as easily is if the framework/template supports any similar convention-based rule that can be used to switch between debug/release (or even better development/staging/production) versions of a file. Think for example of a config.ts file that contains different parameters based on the environment.
I have done some research in the topic, but I was unable to find a conclusive answer:
the old and now retired documentation for the appbuilder platform mentions a (.debug. and .release.) naming convention for files. I don't think this work anymore.
other sources mention passing parameters during the call to tns build / tns run and then fetching them via webpack env variable... See here. This may work, but seems oddly convoluted
third option that gets mentioned is to use hooks to customize the build (or use a plugin that should do the same)
lastly, for some odd reason, the #nativescript/schematics seems to generate a default project that contains two files called environment.ts and environment.prod.ts. I suspect those only work for the web version of the project (read: ng serve) - I wasn't able to get the mobile compiler to recognize files that end with debug.ts, prod.ts or release.ts
While it may be possible that what I am trying to do isn't just supported (yet?), the general confusion an dissenting opinions on the matter make me think I may be missing something.. somewhere.
In case this IS somehow supported, I also wonder how it may integrate with the NativeScript Sidekick app that is often suggested as a tool to ease the build/run process of NativeScript applications (there is no way to specify additional parameters for the tns commands that the Sidekick automates, the only options available are switching between debug/release mode), but this is probably better to be left for another question.
Environment files are not yet supported, passing environment variables from build command could be the viable solution for now.
But of course, you may write your own schematics if you like immediate support for environment files.
I did not look into sharing environment files between web and mobile yet - I do like Manoj's suggestion regarding modifying the schematics, but I'll have to cross that bridge when I get there I guess. I might have an answer to your second question regarding Sidekick. The latest version does support "Webpack" build option which seems to pass the --bundle parameter to tns. The caveat is that this option seems to be more sensitive to typescript errors, even relatively benign ones, so you have to be careful and make sure to fix them all prior to building. In my case I had to lock the version of #types/jasmine in package.json to "2.8.6" in order to avoid some incompatibility between that and the version of typescript that Sidekick's cloud solution is using. Another hint is to check "Clean Build" after npm dependency changes are made. Good luck!
I would like to know which approach is faster, using the pure PHP in the HTML files or using a template engines like Smarty,Twig, ...
What I would particularly like to know is next: which is parsed faster, is the Smarty cache for example faster than using pure PHP?
Which of the template engines is the fastest? I'm about to rewrite simple application where speed is on the first place.
"Depends" is the answer to all your questions.
What is "faster"? Execution time? Development time? Maintenance? Memory overhead? A mixture of them? A template engine is usually trading in some performance (speed, memory) for better development and maintenance.
If you are talking about purely dynamic templating (meaning: template evaluated on every request) PHP will outrun any template engine. This is a nobrainer, really. If you're taking caching into account, a template engine like Smarty may help. Caching is nothing you couldn't implement yourself in plain PHP, though. With Smarty it's just been done for you (and on a far more sophisticated level than you possibly would).
If you are using a framework, say Symfony, it might be wise to use Twig, as Twig and Symfony are tightly integrated. Sure you can use Smarty or plain PHP. The question here is: is it practicable?
Caching makes sense when building sites from datasources like a database or remote APIs. What you are really saving (in a sense of reducing) here are database calls, intensive calculations, etc. Check if you have any time-intensive functions running to build your site. If so, use caching (if you can).
Knowing development/maintenance/convenience/performance trade-offs, I would (always) recommend using a template engine. Being a Smarty developer, I'll, of course, suggest using Smarty. That is unless you're using Symfony, then you might be better of with Twig. Or some other framework featuring some other template engine.
Please ignore posts like Smarty vs. Twig, as they only compare a very limited view of the engines. Don't trust benchmarks you haven't faked yourself™.
In general, though, Smarty 3.1 is a bit faster than Twig. Twig is doing a lot of stuff at runtime (being the time when a template is executed) that Smarty does on compile time (being the time when a template is prepared for execution). Twig is not really pissing away speed here. Twig needs to do certain stuff at runtime by design. They traded a bit of performance for a bit of "convenience" (Accessing arrays and objects with the same notation, for example).
Let's tear the tropes related to this subject apart:
1. Keep logic out of the presentation - Do not put 'code' into your HTML
Anyone who says this and then tells you to go with templating is contradictory:
PHP is an interpreted language - it becomes C code on execution.
The templating 'syntax' is interpreted into PHP
They must stop lying to themselves. Their 'templating syntax' is a programming language built on top of another, which in turn is built on top yet another language - That's inefficient, redundant, and weird.
Furthermore, I fail to see how the very existence of the variables every templating engine that ever was depends on aren't considered logic - Their existence, content and implementation depend on a logical backend.
And what of those templating systems with if/else statements and for loops? That's the very essence of logic - The very concepts which most programming languages utilize. They require variable data which can only be generated or exist through some form of computation.
You cannot serve dynamic content without mixing presentation with logic. It's impossible.
2.1 It's safer...
So, you don't trust your HTML guy?
Case: You think your HTML/CSS guy is stupid and will accidentally print the database password
If that's so, I've got news for you - Your environment is already not safe if sensitive data can be accessed/modified from anywhere within the program.
Case: You think your HTML guy will print random server constants - it's dangerous to allow him, as an individual, to work with server logic
I see - He's either stupid, or hates his job and wants to be fired and therefore will do something dumb like printing session variables. Fine, but to that I'll say...
...Why the heck is this stuff not peer reviewed? Even if he had no access to direct server logic but rather a fancy templating system, he could still equally spread his his stupidity/hatred merely because he has final say on output. Or, he could even be in cahoots with another programmer (If any) and still access server constants and co.
-
2.2.1 Good templating engines automatically sanitize output, or allow the templating-guy to do it himself - he knows better when data should be sanitized
You dummy.
You don't know when output should be sanitized? You couldn't do that yourself..?
Even so, maybe you're just the code monkey and the HTML guy is a web-security HTML-injection specialist, and he should be the one sanitizing output. In that case, giving him access to PHP also allows him to use the likes of htmlspecialchars() rather than whatever the template gives him to do the same thing.
Regarding automatic escaping, provided you're safely passing along content, you can implement such a simple feature within the code you're doing so.
--
2.2 ...and I can control what data is being worked with
Think about classes, functions, etc - You throw data in, they work with it, then you get a result. Typically they do not deal with outside data unless it is handed to them (Doing otherwise is unclear, dangerous and bad practice - Some constants aside). Through these same methods, you can pass on precisely what you need to your output in an efficient, clear and unlimited manor.
--
All that said, it seems like the reason you think your templating engine is any safer than plain code is because you're lacking in several areas of general safety:
You (Or whoever) do not peer review content - You allow individuals to output content.
You are not implementing proper or safe programming practices, and seem to not realize that you can control what's passed along from point A to B.
3. PHP syntax is too hard/difficult to teach the style people
The truth is it's no more complicated than the psuedo-syntax created by template systems such as Smarty, so if this is an issue than dynamic content isn't for you.
The following is in PHP 'short syntax' - Is it too difficult?
<div class='username'><?= $username ?></div>
4. It's too much work to develop my own solution
Though I'd argue it's not, you're free to choose whatever you wish! Choose whatever fits your needs best. They're usually free, not difficult to integrate, and come with loads of features out of the box.
I'm under the impression that most people opt for templating simply because it looks 'neater' within the file - They love thinking that the TPL file is some special thing they created, they like the way the syntax looks; As if by some magic, the variable is 'called' by the little # or # symbol and hops from your logic into the output.
It seems like a trick - The beautiful enchantress (AKA The templating engine) draws you in with her beauty. Though she's appealing to the eye, she's really a blood sucking demon and extracts your soul (Server resources) in exchange for eye candy nobody else sees (Your users would much rather have a faster website and more features funded by the $$$ you're saving on power/server renting)
<title>{{#title}}</title>
Vs
<title><?= $title ?></title>
I will admit, there's only one case I can think of in which templates have any ground over PHP - Portability to other applications. appartisan's answer addresses that. Even so, it's not hard to replace <?= $var ?> with {{#var}} - That's a job for a templating-esque system.
Simply and purely opinion, I think the only advantage is portability. You can re-use templates or views from a template engine into other backend application. Say you're moving your application from PHP to Java, you don't need to refactor the templates.
Otherwise, you're adding complexity, adding other layer of execution ( more time ), more requirements to maintain the application ( you need people that knows that template engine ), and so on. PHP itself it's the best and more featured template engine you're going to get, probably the fastest, and you can do caching also, with the advantage of controlling cache from the backend application, and not from the view.
I will take up this again as things have changed significantly and there are some pieces of evidence missing from the earlier answer.
Without getting deep into why frameworks use template engines over PHP which most do. For some reason there is a constant effort to "fix" PHP with another abstraction layer. Always with claims of simplicity without loss of versatility or performance.
Regardless, the use of PHP is still the fastest and most versatile way of templating. PHP in it's earliest incarnations looked much like a templating language. But let's take a look at the advancements in PHP and place them side by side with the after layers.
Twig and some others claim caching something which was always an addon in earlier versions of PHP. Caching is now a default part of PHP5.5+ (Opcache) and so using PHP as a template language will give more performance enhancements.
Twig and others claim simple syntax for designers. In comparing the syntax of a template engine you'll see that the logic is similar with the only benefit of using a template system like Twig being another layer of security separation between the designer and the underlying system code.
Two very popular CMS Wordpress and Drupal used PHP as their template engines. So the old argument of using a template engine to secure and simplify the use of PHP while designing a website is not really valid in today's web. While Drupal 8 is moving on to Twig it mostly because twig is part of Symfony Framework ( returning to why do frameworks use template engines). Wordpress on the other hand is still using PHP. As Wordpress is growing by leaps and bounds with web designers using PHP to help this happen. Drupals Community has also been split in part by decisions to use Twig and Symfony.
So it would seem that using PHP is the better choice in terms of performance but also the preference for themers and designers going forward. At least all evidence leads to this conclusion.
That being said here's my baseless opinion. I think that using anything other than PHP as template engine in today's web covers some inherent weaknesses in the underlying framework or web application architecture. That weakness being its complexities and complications that cannot be explained easily at the designer or themer level.
If you are writing a lightweight application that has to be small. Keep it small and performing optimally by using PHP and leave the other engines to "enterprise" level groups and projects
I have a problem with the argument that logic and data display must be separared as much as possible. I found that data validation and display actually requires a lot of logic on forms. Information about data type, number range, relation between different data requires a lot of code. The real question is should we use a template language on the server side or Javascript on the client side. By using Ajax and client side code for data display and validation, I end up having very little template code. The biggest problem with template engines is the intoduction of new code rules and syntax. I see the future with PHP, Jquery and Ajax and template engines loosing its appeal.
Ok, I've asked a few related questions here and only ended up with more questions and I realized now it's because I don't have enough background info. So I'll make it more generic:
I need to make a simple web application. Static HTML/JQuery pages will send AJAX POST requests to some server side code, which will:
Read the POST variables passed in
Run some very simple logic
Hit a MySQL database for simple CRUD ops
Return a plain string of data to be consumed by the javascript on the page
I was assuming Ruby was a good choice for this as everyone is raving about how well it's designed, and I've been playing with it - not RoR, just Ruby for simple scripting tasks - and I kind of like it.
My question is, I'm hopelessly confused by the trillion helper libraries and frameworks out there. I don't know what these are and therefore if I need any/all of them: Rack, Sinatra, Camping, mod_ruby, FastCGI, etc.
Would it be easier to just learn PHP and us that? Or can I get away with just dropping my .rb files into the cgi-bin folder(I'm using Apache for hosting) and use the ruby cgi library to get my variables?
EDIT: As far as Rails, I'm just assuming that it's overkill for what I want but I might be wrong. I looked at it, and it seemed cool for generating data based web sites quickly, but that's not what I'm trying to do. I don't want any forms pages for the user. I don't want them entering data or viewing records. I don't even want to return any HTML. I just want a ruby script to sit on the server, get passed a few variables in a post request, and return a JSON string in response. I will need some basic cookie/session/state managment
This is a really easy thing to do in C# and ASP.NET with webservices, but it seems very confusing with the open source technologies.
You don't want to use any feature from a fully blown framework so don't use one. Less code = less bugs = less security nightmares.
CGI
CGI has some performance drawbacks in comparison to other methods, but is still (in my opinion) the simplest and easiest to use one. This is how you use the builtin cgi library:
require "cgi"
cgi= CGI.new
answer= evaluate(cgi.params)
cgi.out do
answer
end
rack
Another low tech easy to use variant would be rack. Rack is an abstraction layer which works for many webserver interfaces (cgi, fastcgi, webrick, …). It's simplicity can be compared to the one of only using cgi. Put the following into a file wich ends with .ru into your cgi directory.
#!/usr/bin/rackup
require "rack/request"
run (lambda do |env|
request= Rack::Request(env)
anwser= evaluate(request.params)
return [200, {}, answer]
end)
This does not seem very different from cgi, but it gives you much more possibilities. If youst execute this file on your local machine rackup will start the webrick webserver. This webserver will deliver the webpages you described in your .ru file.
Other interfaces
fast-cgi
fast-cgi works almost like CGI. The difference is, in CGI your script get's started for every request it has to work on. With fast-cgi, your script only starts once for all requests. There is a library available to write fast-cgi script in ruby.
mod_ruby
mod_ruby is a builtin ruby interpreter for apache. It works analog to mod_php in apache.
mongrel
mongrel is a standalone webserver for ruby applications. This is a simple hello world example with it.
require 'mongrel'
class SimpleHandler < Mongrel::HttpHandler
def process(request, response)
response.start(200) do |head,out|
head["Content-Type"] = "text/plain"
out.write("hello world!\n")
end
end
end
h = Mongrel::HttpServer.new("0.0.0.0", "3000")
h.register("/hello", SimpleHandler.new)
h.run.join
Mongrel is often used for rails and other ruby frameworks. Most people use an apache or something else on port 80. This webserver than distributes the requests to several mongrel servers running on other ports. I think this is totaly overkill for your needs.
phusion passenger
passenger is also called mod_rails or mod_rack. It is a module for apache and nginx to host rails and rack applications. According to their websites rails with passenger uses 1/3 less ram than rails alone. If you write your software for rack, you could make it a little faster by using passenger, instead of cgi or fast-cgi.
Use jQuery and PHP.
Both technologies are well documented, and you should be able to get an application up and running in a matter of hours. You sound like you know a thing or two - talking about CRUD operations and so on - so I won't bore you with examples. And as far as JSON goes, there are probably a million PHP libraries out there, for outputting JSON objects.
Sinatra is very simple to learn and use. It's also easy to deploy with the use of Phusion Passenger (which is like mod_php for ruby frameworks like Rails and Sinatra). Instructions here: http://blog.squarefour.net/2009/03/06/deploying-sinatra-on-passenger/
If you find that you need more than what Sinatra will give you, I recommend Rails. Setting up that with Passenger is even easier since hardly any configuration is required. (see modrails.com).
PHP is very easy to use because it's designed specifically for this sort of thing. Want to read POST variables? They're in $_POST. Want to query MySQL? mysql_query("SELECT `something` FROM `table`");. And if you ever need help, Google searches for "php what_you_need_to_do" almost always return results on php.net, which is very helpful.
And for what you're doing, you don't need any additional frameworks.
I am curious about what I perceive to be your resistance to trying Rails. You say that you want "to spend more time on the scripting itself and less on configuration", and yet you seem to dismiss Rails out of hand. Rails is all about convention over configuration. If you take the time to learn how Rails does things, you can get an incredible amount of functionality "for free" just by following the conventions of the framework.
If you want to make a simple web app, Rails is really a very painless and good way to start. You can use a sqlite database and not even mess with MySQL (won't scale, but for learning or simple apps it's fine). It's true that there are simpler frameworks, but since you seem new to web programming, I'd recommend that you start with what will get you the most support in terms of documentation and knowledgeable folks. Follow the old adage: Get it working first, then optimize later.
The only sticking point I can see is the Apache integration... The consensus on Rails deployment these days seems to be focused on using lightweight httpds in place of Apache. There is a mod_fcgid which seems to be the best way to do it with Apache (mod_ruby is deprecated, buggy and slow, last I read) if you can do custom mods. Or there's Phusion Passenger, which seems to be the latest and greatest way to do it. Running Rails in a standard CGI environment will yield awful performance (but that goes for any CGI framework, really) due to the overhead of executing the interpreter + framework for every request. You'll get much better performance if you go with something that keeps the interpreter + framework in memory.
I personally like Django. I had a problem with Ruby on Rails where I just got overwhelmed by everything when I just wanted to do something simple, which it sounds like you want to do (since you said ROR feels like overkill). The cool thing I found with Django is that if you WANT everything, then you can get everything by plugging it in...but if you want less then you just don't plug in that technology and it's that much more lightweight.
Take for example "views". Django, like ROR, uses MVC. But if you just want to return a string of data and don't need the view, then you don't need to plug in the view. But if later on you decide that it will be more organized in a view then you can easily plug it in at that time.
Here's their website: http://www.djangoproject.com/
I'm starting to use Dojo; this is (essentially) my introduction to AJAX. We have a Java backend (torque / turbine / velocity) and are using the jabsorb JSON-RPC library to bridge Java and Javascript.
What do I need to know? What is the big picture of Dojo and JSON, and what are the nasty little details that will catch me up? What did you spend a couple of days tracking down, when you started with Dojo, that you now take for granted? Thanks for any and all tips.
The first thing to do is get familiar with the Dojo Object Model. JavaScript does not have a class system so the Dojo toolkit has created a sort of "by convention" object model that works rather well but is very different to how it works in Java for example.
The reason I suggest getting familiar with it is so you can dig into the code base whenever you start experiencing issues. The documentation available has improved significantly over the past year, but every now and then I find myself having to work out a bug in my code by learning exactly how the Dojo code involved works.
Another tip is to make use of the custom build feature which will significantly improve performance once your application is ready.
As a general tip on DHTML programming, use firebug (a plug-in for Firefox). It allows JavaScript debugging, DOM inspection, HTML editing in real-time and a whole lot more. I've become totally reliant on it now when I'm working in DHTML!
Good luck!
I too just dove head first into Dojo, they have a good API documentation at http://api.dojotoolkit.org/. Even Dojo Campus has some good examples of the plug ins.
If you ask me O'Reilly's Dojo: The Definitive Guide is the best Dojo book on the market.
I also would like any tips and pointers from the Dojo masters.
Cheers
Make sure documentation you read pertains to as recent a release as possible, since a lot has changed very quickly in the Dojo architecture.
Also a great way to see how some Dojo or Dijit widget is used is to look at the source code for the tests - for example, the DataGrid has poor documentation but the tests show a lot of use cases and configurations.
Sitepen is a good resource for Dojo articles.
Also, read up on Deferred (andDeferredList), as well as hitch() - two extremely flexible and powerful features of Dojo. SitePen has a great article on demystifying Deferreds.
Check out plugd, a collection of Dojo extensions that make some things more convenient or adds some clever functionalities to the language. It's made by one of the core Dojo authors so it's rather reliable. It even brings some jQuery niceties into the framework.
Some more things: look into data stores, they're very useful and a much cleaner way to handle Ajax. DojoX has a lot of nice ones too, just remember that DojoX ranges in how well documented or how experimental the components are. Learn the differences between dojo.byId and dijit.byId, as well as the HTML attributes id versus jsId (again, Sitepen has an article).
A couple of things that caught me when I started writing widgets where:
[Understand what dojoAttachPoint, dojoAttachEvent, containerNode and widgitsInTemplate do][1]
have a firm grasp of closures,
Get your head around deferreds
understand ItemFileReadStore, ItemFileWriteStore and stores in general
You can look at stores like a ResultSet (sort of) as well you can data bind them to widgets.
With these major concepts you can start to put together some compelling applications.
Generally what I do is I build a JavaScript facade around my service calls and then I will scrub the response into a store by attaching the first callback in the facade, that call back converts the results into a store and then returns it. This allows me to not hard bind my services to Dojo constructs (so I can support mobile, etc.) while also retuning the data from the facade in a format that data aware widgets expect.
As well if you are doing Java service development you my want to look into JAX-RS. I started out using JSON-RPC which became JABS-ORB but after working with JAX-RS I prefer it, as it integrates well with JPA-EJB and JAXB.
First read how to configure Dojo in your application. Try to understand basic structure of Dojo like if we are writing dijit.form.Button or dijit/form/Button it means Button.js resides in dijit/form folder. Try to understand require, define, declare modules of Dojo. This is enough to start Dojo Toolkit.
Very important fact, indulge with your own sample project using Dojo.