How to creating code highlighted blocks on your website - javascript

I have written a small PHP framework and I want to make a website where I explain some basic features.
I want to display blocks of php code. Is there an easy to do this, preferably without JavaScript.
I want to have section kind of like displayed below:
// This function takes in a value and return it
public function getname($name){
return $name;
}

For the server-side there are a few options already out there:
The built-in highlight_file and highlight_string
Highlight source code in your PHP application
GeSHi - Generic Syntax Highlighter
CHIP: Code Highlighting in PHP
There are others, but just letting you know there are libraries available.

On my Tumblr blog I use Prettify for syntax highlighting. You can have a look here.
I'm really pleased with its simplicity and it support a lot of languages out of the box.

You can take a look at http://alexgorbatchev.com/wiki/SyntaxHighlighter

Related

Localize / Internationalize Static & Dynamic Content, Client Side

Been trying to figure out a solution to internationalize a shopify store. Would really like to use JS or jQuery and switch languages instantly/client side without a reload using JSON-files for storing all language snippets..
There are a couple of really smart options (like localizejs.com), but they are rather expensive over time. Ideally we do not even need a super fancy backend and wouldn't mind "just" editing the language-files manually.
JSON could look like this:
{
"english": {
"Cart":"Warenkorb",
"Products":"Produkte",
"Contact":"Contact"
}
We appreciate any solution you can recommend! We need to be able to replace strings that contain elements like "href" as well though:
<div class="lang“>Replace <a href="#“>a Link</a></div>
How is this tackled usually?
Nowadays people are trying jQueryi18n plugin. May be you can check whether it can suffice your requirements. Its minified version size is upto 5KB. Its very easy to use in your project.
http://www.SiteTran.com/ will enable you to switch languages on the client side, and it's free. It also can provide usable SEO urls (for your HREF's) and it only requires a snippet of javascript for integration.
If you want to do it on your own, you can just simply a JSON file with all of the translations and then with javascript load the text based upon the language.

How to make the javascript code easy to maintenance

All, I am working on a highly interactive web application which will need a lot of jquery or js code, And I'm finding that my code is becoming a little hard to maintain and is not all that readable. Sometimes even the author can't find the specified code.
So far what I had done for the clear code is below.
One js component in one js file .(for example. CustomTab.js is a tab component in my app.)
Using the templete to generate component HTML based on JSON.
Using Jquery UI.
Unobtrusive JavaScript.
Is there any other points I need pay attention? Anyway, Any suggestion or recommend technique for making js library/framework easy to miantanance is appeciated, thanks.
I could suggest you to use module pattern together with RequireJS to organize your JavaScript code. For the production you'll be able to use RequireJS optimizer to build your modules into one JavaScript file.
Also if you're expecting that your client-side application will be huge, consider to use some JavaScript MVC framework like Backbone.js together with the server-side RESTful service.
I use this namespacing pattern for my libraries:
MyLibrary.ListView.js:
var MyLibrary = MyLibrary || {};
MyLibrary.ListView = {
doSomethingOnListView: function() {
...
return this;
},
doSpecialThing: function() {
...
return this;
},
init: function() {
// Additional methods to run for all pages
this.doSomethingOnListView();
return this;
}
};
Whichever page needs this:
<script type="text/javascript" src="/js/MyLibrary.ListView.js"></script>
<script type="text/javascript">
$(function() {
MyLibrary.ListView
.init()
.doSpecialThing();
});
</script>
You can even chain methods if a certain page requires an additional function.
This is exactly the same question which I ask myself each time. I think there are few ways to get easy maintaining code.
Contribute in javascript opensource projects and understand how they solved that problem. I think you can gather some unique solution from each project and common part of projects structure will answer to your question about maintenance.
Use prepared solutions like backbone, knockout, ember or angularjs if I am not mistaken angular doesn't give you structure but provide you powerful tool for creating pages with less code. Also check todomvc for ready-made solutions.
Read books and try to create some structure for your needs. It will be difficult and long but result (maybe few years later :)) will be awesome.
Currently I'm also working on a JS framework for my company. What I'm doing is I use OOP elements for JS. In other words I'm implementing similar code to C# libraries(not that similar, simulating will be the correct word). As an example in C# you use Microsoft.Window.Forms, so I can use JSOOP and use method extending and overriding to create the same scenario. But if you gone to far in your project converting your JS code to JSOOP will be time consuming.
use JSLint, this will validate your code and bring down to a readable, script engine friendly code. Though JSLint is very strict so you can use JSHint also.
using seperate file for each component is a good idea I'm doing it also.
If you like you can download the jQuery developers version and you can have a general idea how they created the framework. I learned lot of thing looking at jQuery framework!

Ajax applications with perl backend - how to?

There are already questions about the Perl+AJAX, like here, here or here and several others. They're more than 2 years old and I was hoping for some new stuff.
The questions are:
What is the most preferred method today making AJAX apps with a Perl backend?
Are there some active and commonly used Perl modules that help build AJAX based applications?
Something, for the usual workflow:
if clicked this button (or changed this field.. etc),
POST these data to the server,
read the JSON answer,
and update this/these DIV(s) in a DOM... etc.
This question is can be classified as vague, but I'm really lost and need help with this: what is the most common way making AJAX apps in the Perl world, TODAY.
Looking for a helper module that help me build the browser-side javascript.
I found these:
https://metacpan.org/pod/OpenThought
https://metacpan.org/pod/HTML::AjaxTags
https://metacpan.org/pod/CGI::Ajax (but this is CGI based and IMHO not the best for Plack world)
These modules have not been updated for several years. Are they stable and in use? Or are they deprecated and is there some better way? (for the modern Perl technologies - like Plack).
UPDATE
As I read answers, I'm thinking that the main problem is probably in my English. I don't know how to express myself right.
I know Perl. Maybe I'm not an expert, but I wrote several thousand lines of code. I know Dancer, and already write some apps in Mojo...::Lite. Know JSON{::XS} and I know how AJAX works.
Now (for some reason) I prefer using Mason2, with Mason::Plugin::RouterSimple and several other CPAN modules and Moose. Catalyst, Jifty are too big for my needs.
Back to the question:
My favorite JS framework is jQuery, I'm using it in several projects for modal windows, or accordions, tabs etc.
BUT
My main problem is exactly in Sismetic's answer. I don't want to write JavaScript. Don't like it. (Don't know it very well, and hate every language where I must write something like: var arr = new Array(); instead of my #arr)
So, looking for a solution, how I can minimize (or in the ideal world - totally eliminate) the need of writing the JavaScript code. Don't want write into my templates
$('.clickableButton').click(function(e) {
.... etc... etc..
)}
but something like:
$ajax->make_button( -onchange=>$url, -updatedom=>'#thisdiv", some_special_button_description_in_perl );
$tohead .= $ajax->gen_libs();
$tohtml .= $ajax->gen_html();
$jsdocready .= $ajax->gen_jsinitcode();
An in my templates will output only $tohead in the head part (so include jQuery), $tohtml will come into body, and $jsdocready will come into the end of body as JavaScript init code.
Offcourse, the above is an very stupid example, but hopefully shows what I mean. Simply: The ideal solution was (probably does not exists) is totally eliminate the need writing JavaScript, only Perl code what will generate the needed JS.
Therefore I mentioned the above modules, especially https://metacpan.org/pod/OpenThought, because these really help minimize writing JavaScript. The problem is - these have not updated for 2 years. ;( And unfortunately - I don't know any others.
The reason you're not getting answers isn't just the vagueness of the question. The problem space is very wide and has a many angles of attack.
Let's clarify that the "x" in Ajax shouldn't be taken to mean XML anymore. JSON is obviously more natural and doesn't suffer from nearly as many problems so all my advice will point toward it.
What hobbs said already is right on. You do not want to mess with the server-side code much at all but adopt a framework. This is not because dealing with Ajax is hard in Perl; it's trivial. It's because the problem space gets messy quickly and you'll end up repeating your code in endless minor variations. So–
Perl/Server-side
Any of these will make you happy eventually. They all have a learning curve. There are other options but these are the Best™.
Catalyst (Catalyst::View::JSON)
Dancer (Dancer::Serializer::JSON)
Mojolicious (prefer Mojolicious for HTML5/Websockets)
Deployment SHOULD be Plack/PSGI based.
Take the time to really learn the core of Perl's Ajax handling: JSON(::XS) so you know what the views in the various frameworks do under the covers.
JavaScript/Client-side
This is essentially an embarrassment of riches at this point.
jQuery
Many Perl hackers like this kit; it seems to hit the same sweet spot Perl does. I adore jQuery.
Dojo
I'm not a fan — they had the worst documentation possible in early versions and broke compatibility while deleting what little docs used to exist — but it's well-liked in its current version.
MochiKit
MooTools
YUI
ExtJS
This, now distant, fork from YUI is the 800lb gorilla of client-side JS. I personally dislike it because of its lack of graceful degradation, et cetera, but it is highly regarded and very sharp looking out of the box.
I personally dislike and can't recommend prototype and though I've never used it I also chose not to put script.aculo.us on the list.
There are plenty of other amazing specialty kits out there too; e.g., Modernizr. When you are looking into JS, consider how important standards compliance and forward-looking features like CSS3, HTML5, extended event handling like multi-touch are to what you'll do. Good luck and have fun.
Update: Possibly of further interest
Jemplate – templating in JavaScript
Catalyst::View::Jemplate
Jifty – YAWF
Looking for "ajax" isn't really what you need. Just use a web framework of your choice that has good facilities for serialization, working with Accept headers, etc. For example Catalyst and Catalyst::Action::REST, or Dancer. Don't write Perl that writes Javascript, it will only make you sad.
I use CGI::Application as my base framework and CGI::Application::Plugin::JSON to return JSON data to jQuery.
If you want to generate HTML code with a Perl module, I would recommend CGI.pm:
...
use strict;
use warnings;
#CGI is shipped along perl, I think
use CGI;
my $CGI = CGI->new();
my $return_string = '';
#From CGI documentation on CPAN
#http://search.cpan.org/~markstos/CGI.pm-3.55/lib/CGI.pm
$return_string .= $CGI->header;
$return_string .= $CGI->start_html('hello world');
$return_string .= $CGI->h1('hello world');
$return_string .= $CGI->button(-name => 'button_name',
-value => 'Click Me!',
#Javascript event if needed
-onClick => "do_something()"
);
$return_string .= $CGI->end_html;
print $return_string;
Or(as I dont like the latter method) you could just write it on perl(generating it yourself manually):
use strict;
use warnings;
#Needed header, otherwise will return error
print "Content-type: text/html\n\n";
#return random number from 0 to 100
my $random_number = int(rand(101));
my $HTML_generated_string = qq|
<html>
<head>
<title>HTML generated manually with perl</title>
</head>
<body>
<h1>Hello world</h1>
Bla bla bla Heres the random number $random_number
</body>
</html>
|;
print $HTML_generated_string;
Other than that, I dont know any extra modules to do it. I normally do it by hand, or write a template(with CGI::Application).
I don't think the thing you are asking for exists. You can't write AJAX apps without using JavaScript. If someone invented a way to do JavaScript without JavaScript it would be a major project and not one person's weekend CPAN module.
I suggest rethinking your view of JavaScript. JavaScript is an excellent language and JQuery is great as well. There is a lot of bad JavaScript code out there, but there is good JavaScript code as well. Just like there are good and bad practices in the Perl community. I'd suggest you keep an open mind and take another look at JavaScript and make sure you really know the foundations well. Sometimes my frustration with a language just means I haven't learned it very well.
There are some very cool things happening in the JavaScript world. I admit its chaotic and decentralized and there is a lot of different stuff to know about and thats exhausting but its also exciting that so much is happening.
You probably already know about these resources, but just in case: FireBug, Mozilla Developer Network JavaScript docs, and JavaScript Garden
See Dancer::Plugin::Ajax on cpan
http://metacpan.org/pod/Dancer::Plugin::Ajax

What is the best way to organize JS code in webapps where the main "meat" is still server side?

When building webapps with MVC web framworks like Django, Kohana, Rails and the like, I put together the application without JS-driven components initially, and then add them afterwards as "improvements" to the UI.
This approach leads to non-intrusive JS, but I don't have a good "standard" way of how to go about organizing the JS work. Most of the JS I write in apps like these are 10-30 line JQuery snippets that hook into some very specific part of the UI.
So far I often end up inlining these things together with the part of the UI they manage. This makes me feel dirty, I'd like to keep the JS code as organized as the python / php / ruby code, I'd like for it to be testable and I'd like for it to be reusable.
What is the best way to go about organizing JS code in a setup like this, where we're not building a full-blown JS client app, and the main meat is still server side?
I am also very interested in what other people have to say about this. The approach I've taken is to use object literal notation to store the bulk of the function, and store these in one file included on all pages (the library)
uiHelper = {
inputDefault:function(defaulttext){
// function to swap default text into input elements
},
loadSubSection:function(url){
// loads new page using ajax instead of refreshing page
},
makeSortable:function(){
// apply jQuery UI sortable properties to list and remove non javascript controls
}
}
Then I include a .js file on any page that needs to use the library that ties the elements on that page to the function in the library. I've tried to make each function as reuseable as possible and sometimes the event binding function on the page calls several of my library functions.
$(document).ready(function(){
$('#mybutton').live('click',uiHelper.loadSubSection);
//more complicated helper
$('#myotherbutton').live('click',function(){
uiHelper.doThisThing;
uiHelper.andThisThing;
});
});
edit: using jsDoc http://jsdoc.sourceforge.net/ notation for commenting for these functions can produce documentation for the 'library' and helps keep your code easy to read (functions split by comments).
The following question is along similar lines to your own - you should check it out...
Commonly accepted best practices around code organization in JavaScript
When dealing with JS code, you should first analyze whether it will be used right away when the page loads. If it's not used right away (meaning the user must do something to invoke it) you should package this into a JS file and include it later so the load time is perceived faster for the user. This means that anything that the user will sees should go first and JS related to the functionality should be imported near the end of the file.
Download this tool to analyze your website: http://getfirebug.com/
If the JS code is small enough, it should just be inline with the HTML.
Hope that helps a bit.
For quick little user interface things like that I put everything into a single javascript file that I include on every page. Then in the javascript file I check what exists on the page and run code accordingly. I might have this in UIMagic.js for example. I have jQuery, so excuse those jQuery-isms if they aren't familiar to you.
function setupMenuHover() {
if ($("li.menu").length) { // The page has a menu
$("li.menu").hover(function() { ... }, function() { ... });
}
}
$(setupMenuHover);
function setupFacebookWizbang() {
if (typeof FB != "undefined") { // The page has Facebook's Javascript API
...
}
}
$(setupFacebookWizbang);
I've found this to be a sane enough approach.
My preferred method is to store inline javascript in it's own file (so that I can edit it easily with syntax highlighting etc.), and then include it on the page by loading the contents directly:
'<script type="text/javascript">'+open('~/js/page-inline.js').read()+'</script>'
This may not perform well though, unless your templating library can cache this sort of thing.
With Django you might be able to just include the js file:
<script type="text/javascript">
{% include "js/page-inline.js" %}
</script>
Not sure if that caches the output.
If you are still worried about being 'dirty', then you could check out the following projects, which try to bridge the server/client side language mismatch:
http://pyjs.org/ (Python generating JavaScript)
http://code.google.com/webtoolkit/ (Java generating JavaScript)
http://nodejs.org/ (JavaScript all the way!)

JavaScript code completition done right?

I've tried some of the editors/IDEs regularly recommended for coding JavaScript (Aptana, WebStorm, ...) but none of them has a satisfying autocomplete functionality. I'm probably spoiled by Microsoft's IntelliSense for .NET. There is some JavaScript-IntelliSense in WebDeveloper, but that seems to be a stripped-down version. The best I've found so far is WebStorm, but its code completition is easily distracted by imported libraries (offering hundreds of suggestions) and identical function names.
Did I miss an editor/IDE that uses refactoring (or something else) to offer proper code completition, so that it really "knowns" what that variable-name stands for, I just put a dot behind? Or is something like this on its way?
I always recommend Komodo Edit from ActiveState (now up to version 6, with support for HTML 5 and CSS3 as well as recent versions of Javascript, PHP, etc.) Note that you may have to install addons for the languages you're working in, but you should find them through the Mozilla-like Addon manager.
Also supports jQuery and even lets you use jQuery (along with vanilla Javascript or Python) in its powerful macro IDE.
Code completion example:
<script type="application/x-javascript">
var obj = {};
obj.personnel = [{firstName:"John", lastName:"Brick", age:43},
{firstName:"Jane", lastName:"Motte", age:26}
];
// now type obj. and code completion immediately offers you "personnel"
// note: file must be saved for the app to find all members of declared
// variables, but I save about every 10 seconds so it's not a problem
</script>
The best I've found so far is
WebStorm, but its code completition is
easily distracted by imported
libraries (offering hundreds of
suggestions) and identical function
names.
This comment confuses me. If you import the libraries, and your code is using them, why is it bad to include the function names in the code completion suggestions? Wouldn't you want to have jQuery's functions included if you're using it?
If you're using Microsoft's IntelliSense with jQuery, does it stick to its guns and only show JavaScript core functions? Sounds limited to me, unable to be smart when I add libraries.
Or is something like this on it's [sic] way?
It sounds to me like you want a clairvoyant interface. I don't think it is on the way anytime soon.
By the way, "it's" == "it is"; "its" is the possessive.

Categories

Resources