Get the loaded LESS file and compile it on demand - less

I'm trying to compile a small LESS portion of code and mixing it with a bigger one already compiled in the page.
I thought there was some way to reuse the compiled less or maybe load it again, mix it with the newer code and then compile it mixed in the page.
I thought to load it in some way like the example below:
var runtime_less = '#bg:red; .selector { background-color:#bg; }';
var library_less = '#var:bla bla bla...';
var library_parser = new(less.Parser)({
paths: ['.', './lib'], // Specify search paths for #import directives
filename: 'css/full_library.less' // Specify a filename, for better error messages
});
frontsize_parser.parse('', function (e, tree) {
library_less = tree;
});
var runtime_parser = new(less.Parser)({});
runtime_parser.parse(library_less, function (e, tree) {
// this should be inside some load event
$("#container-style").text(library_less.toCSS() + ' ' + tree.toCSS());
});
Does exist some way to get the current page loaded LESS file and treat it in some way?
Or does exist some way to load LESS files and then mix the LESS data with a string with additional LESS code?

with t.less containing:
#color: lightgreen;
You can use the following code:
<link type="text/css" href="t.less" rel="stylesheet/less">
<script>
less = {
env: "development"
};
</script>
<script src="/less.js/dist/less.js"></script>
<script>
var tmp = less.parse;
less.parse = function(input,option,callback) {
tmp(input + ' h1 {color:#color;}',option,callback);
}
less.refreshStyles();
</script>

Related

How to properly set contents in a gitbook-plugin's block?

Get the path of a file in gitbook head
This question touch the possibility to get a path of a specific file.
For example, to get some content, before page loads in a gitbook, is possible to add in "head:end" some customizations. This work fine when we need jquery loaded in `.
module.exports = {
book: {
...
/* Load files */
html: {
'head:end': function(current){
console.log()
var p = current.basePath+"/"+current.staticBase+"/plugins/myplugin/jquery-latest.min.js";
...
}
...
Get the path of a file in gitbook block
But in a custom block, how i do this?
blocks: {
myblock: {
process: function(current) {
//current isnt same... :(
// h
console.log(current);
var p = current.basePath+"/"+current.staticBase+"/plugins/myplugin/"+current.args[0];

Format/Layout for cshtml page

I got a lot of help regarding this issue earlier but the issue hasnt been completely resolved for me. I am stuck at another thing now. I am returning a response from my controller and receiving it in the Index.cshtml like this:
var rData = #Html.Raw(Json.Encode(Model.WarehouseResults));
Now I need to assign this data to slickgrid somewhat like this:
<script type="text/javascript">
var from = 0, to = from + rData.length;
//data.length = parseInt(resp.total);
for (var i = 0; i < rData.length; i++) {
data[from + i] = rData[i];
data[from + i].index = from + i;
}
onDataLoaded.notify({ from: from, to: to });
grid = new Slick.Grid("#myGrid", rData, columns, options);
etc etc...
</script>
Now, the problem is, I dont know where exactly to receive the data. As in, where do I put this line:
var rData = #Html.Raw(Json.Encode(Model.WarehouseResults));
If I put it above the tag (but inside the #Scripts section), I get an error saying rData is not defined. Then when I put it inside the tag, I get a syntax error saying: "IHtmlString HtmlHelper.Raw(String value) (+1 overloads) returns markup that is not HTML encoded".
Where exactly should this line go? Is there a standard format for a cshtml page, like which sections go where? If so, can someone provide a link or something for it?
Using your code in MVC 5:-
var rData = #Html.Raw(Json.Encode(Model.WarehouseResults));
I find that the semi-colon at the end of the line causes a syntax error.
A solution which I am currently using (my example is for JQuery autocomplete) which should also work for your example is as follows.
Create the javascript variable code completely within the HtmlHelper. This is placed within the view's #section Scripts.
#section Scripts {
<script type="text/javascript">
#Html.Raw("var existingPersons = " + Json.Encode(this.Model.ExistingPersons) + ";" )
#Html.Raw("var settlementInformation=" + Json.Encode(this.Model.SettlementInformation) + ";")
$(function () {
$("#personName").autocomplete({
source: existingPersons
});
$("#settlementInformation").autocomplete({
source: settlementInformation
});
});
</script>
}
At the client side this appears in the <head> element as expected
<script type="text/javascript">
var existingPersons = ["Person 1","Person 2"];
var settlementInformation=["Settlement Type 1"];
$(function () {
$("#personName").autocomplete({
source: existingPersons
});
$("#settlementInformation").autocomplete({
source: settlementInformation
});
});
</script>
I've not tried this in other versions of MVC

fairytale about mvc, require.js and angular. is there happily ever after?

So. Once upon a time there were four magical creatures: asp.net mvc, require.js and angular. And one wise wizard decided to put them in the same house, and let for every single view of asp.net to have its own "code-behind" javascript file;
first he added to the _Layout.cshtml
<script data-main="/main" src="~/Scripts/require.js"></script>
and then he created main.js in the root:
require.config({
baseUrl: "/Scripts/",
paths: {
'jquery': 'jquery-1.9.1.min',
'jquery-ui': 'jquery-ui-1.10.2.custom.min',
'angular': 'angular.min',
'ng-grid': 'ng-grid-2.0.2.debug'
},
shim: {
'jquery': { exports: "$" },
'underscore': { exports: "_" },
'jquery-ui': ['jquery'],
},
});
// Standard Libs
require(['jquery','jquery-ui','underscore','angular']);
nothing fancy and magical yet. But then he created an html helper as such:
public static MvcHtmlString RequireJs(this HtmlHelper helper)
{
var controllerName = helper.ViewContext.RouteData.Values["Controller"].ToString(); // get the controllername
var viewName = Regex.Match((helper.ViewContext.View as RazorView).ViewPath, #"(?<=" + controllerName + #"\/)(.*)(?=\.cshtml)").Value; //get the ViewName - extract it from ViewPath by running regex - everything between controllerName +slash+.cshtml should be it;
// chek if file exists
var filename = helper.ViewContext.RequestContext.HttpContext.Request.MapPath("/Scripts/views/" + controllerName.ToLower() + "-" +
viewName.ToLower()+".js");
if (File.Exists(filename))
{
return helper.RequireJs(#"views/" + controllerName.ToLower() + "-" + viewName.ToLower());
}
return new MvcHtmlString("");
}
public static MvcHtmlString RequireJs(this HtmlHelper helper, string module)
{
var require = new StringBuilder();
require.AppendLine(" <script type=\"text/javascript\">");
require.AppendLine(" require(['Scripts/ngcommon'], function() {");
require.AppendLine(" require( [ \"" + module + "\"] );");
require.AppendLine(" });");
require.AppendLine(" </script>");
return new MvcHtmlString(require.ToString());
}
and then he could use it in _Layout.cshtml just like that:
#Html.RequireJs()
and if you were listening carefully to the story, you probably noticed that there was also Scripts/ngcommon.js file to manually bootstrap angular.js and have commonly used angular directives and services
require(['angular', 'jquery'], function() {
angular.module("common",[]).directive('blabla', function() {
return {
restrict: 'A',
scope: { value: "#blabla" },
link: function(scope, element, attrs) { }
}
});
//manually bootstrap it to html body
$(function(){
angular.bootstrap(document.getElementsByTagName('body'), ["common"]);
});
});
And here comes the magic: from now on if it was a javascript file in \Scripts\views named as controllerName-viewName.js as home-index.js for Home\Index.cshtml it would be automagically picked up by require.js and loaded. Beautiful isn't it?
But then the magician thought: What If I need to load something else (like ng-grid) and that something should not be injected into common angular module because not all the pages will be using it. Of course he could always manually bootstrap another module into a page element in each code-behind javascript where he needed, but he's not wise enough to find answer to the question:
Is it possible to inject some angular.js component (like ng-grid) directly into a controller, without having it as a part of the app module?
If I understand magician's idea right, then it is possible to go on by splitting your application into sub-modules being defined as a collection of components.
It will work if he sets up dependencies for main myApp module like:
var myApp = angular.module('myApp', ['Constants', 'Filters', 'Services', 'Directives', 'Controllers']);
myApp.Constants = angular.module('Constants', []);
myApp.Controllers = angular.module('Controllers', []);
myApp.Filters = angular.module('Filters', []);
myApp.Services = angular.module('Services', []);
myApp.Directives = angular.module('Directives', []);
Then each of sub-modules: Services etc. - can be extended with single component, like:
myApp.Controllers.controller('MyController', function () {});
myApp.Services.factory('myService', function () {});
myApp.Directives.directive('myDirective', function () {});
myApp.Filters.filter('myFilter', []);
myApp.Constants.constant('myConstant', []);
That way main application module is loaded with several sub-modules, but each structure is not important. It makes possible to include individual controllers, services, directives and filters on each page served from back-end - magician just needs to be sure that all needed dependencies are loaded.
DI is the magic key for having separate angular codebehind in MVC views.
You don't even need the requirejs at all, because angular is a dependency injector and module loader by nature, angular.bootstrap is the magic place to start.
So let wizard became more powerfull with the spell - $inject.
var TmplController = function($scope, $compile, $http... // any module itself
{
this.parts = ['legs','arms','head'];
$scope.dynamicPageTemplate = function($compile)
{
$compile('<div><p ng-repeat="each in parts">{{each}}</p></div>' )( $scope );
}
}
TmplController.$inject = ['$scope','$comple', '$http']; //try legs or head
refer complete annotated source of angular-scenario.js from https://github.com/angular/bower-angular-scenario, and you will find how to inject code with define manner helpers.

usemin revved filenames and requirejs dependencies

I'm running into the following problem with requirejs and usemin:
I want to setup a multipage application, where I dynamically load modules that only contain page specific functionality (e.g. about -> about.js, home -> home.js). I could go ahead and pack everything in a single file, but that just leads to a bigger file size and overhead on functionality that isn't necessary on each site! (e.g. why would I need to load a carousel plugin on a page that doesn't have a carousel!)
I checked out the example https://github.com/requirejs/example-multipage-shim
That is in fact a great way to deal with it, until I bring usemin into the game. After revving the filenames the src path of each script tag is updated, but what about the dependencies?
<script src="scripts/vendor/1cdhj2.require.js"></script>
<script type="text/javascript">
require(['scripts/common'], function (common) {
require(['app'], function(App) {
App.initialize();
});
});
</script>
In that case, require.js got replaced by the revved file 1cdhj2.require.js. Great!
But the required modules "common" and "app" no longer work since common became 4jsh3b.common.js and app became 23jda3.app.js!
What can I do about this? Thanks for your help!
(Also using Yeoman, btw)
It's a tricky problem and I'm sure somebody else fixed in in a more elegant way, but the following works for me.
I might publish this as a grunt plugin once it's a little more robust.
Taken from my Gruntfile:
"regex-replace": {
rjsmodules: { // we'll build on this configuration later, inside the 'userevd-rjsmodules' task
src: ['build/**/*.js'],
actions: []
}
},
grunt.registerTask('userevd-rjsmodules', 'Make sure RequireJS modules are loaded by their revved module name', function() {
// scheduled search n replace actions
var actions = grunt.config("regex-replace").rjsmodules.actions;
// action object
var o = {
search: '',
replace: '', //<%= grunt.filerev.summary["build/js/app/detailsController.js"] %>
flags: 'g'
};
// read the requirejs config and look for optimized modules
var modules = grunt.config("requirejs.compile.options.modules");
var baseDir = grunt.config("requirejs.compile.options.dir");
var i, mod;
for (i in modules) {
mod = modules[i].name;
revvedMod = grunt.filerev.summary[baseDir + "/" + mod + ".js"];
revvedMod = revvedMod.replace('.js', '').replace(baseDir+'/','');
o.name = mod;
o.search = "'"+mod+"'";
// use the moduleid, and the grunt.filerev.summary object to find the revved file on disk
o.replace = "'"+revvedMod+"'";
// update the require(["xxx/yyy"]) declarations by scheduling a search/replace action
actions.push(o);
}
grunt.config.set('regex-replace.rjsmodules.actions', actions);
grunt.log.writeln('%j', grunt.config("regex-replace.rjsmodules"));
grunt.task.run("regex-replace:rjsmodules");
}),
You can also use requirejs' map config to specify a mapping between your original module and your revved one.
Filerev outputs a summary object containing a mapping of all the modules that were versioned and their original names. Use grunt file write feature to write a file in AMD way with the contents being the summary object:
// Default task(s).
grunt.registerTask('default', ['uglify', 'filerev', 'writeSummary']);
grunt.registerTask('writeSummary', 'Writes the summary output of filerev task to a file', function() {
grunt.file.write('filerevSummary.js', 'define([], function(){ return ' + JSON.stringify(grunt.filerev.summary) + '; })');
})
and use this file in your require config so that the new revved modules are used instead of old ones:
require(['../filerevSummary'], function(fileRev) {
var filerevMap = {};
for (var key in fileRev) {
var moduleID = key.split('/').pop().replace('.js', '');
var revvedModule = '../' + fileRev[key].replace('.js', '');
filerevMap[moduleID] = revvedModule;
}
require.config({
map: {
'*': filerevMap
}
});
The filerevMap object that I created above is specific to my folder structure. You can tweak it as per yours. It just loops through the filerev summary and makes sure the keys are modified as per your module names and values as per your folder structure.

How to show the compiled css from a .less file in the browser?

What is the best way to show the resulting css from files compiled with less.js in the client.
In other words, how can i fill a div with the resulting css?
I need to display the result on the page, any way to do this?
THanks!
update
As already pointed out in the comments by #ertrzyiks you should replace less.parse with less.render for Less v 2.x:
var lessCode = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
var options = {}
lessCode = xmlhttp.responseText;
less.render(lessCode, options, function (error, output) {
if(!error) {
document.getElementById('lesscode').innerHTML = output.css;
}
else document.getElementById('lesscode').innerHTML = '<span style="color:red">' + error + '</span>';
});
}
};
xmlhttp.open("GET","important.less",true);
xmlhttp.send();
see also: How to detect and print changing variables LESS
But since Less v2:
In the browser, less.pageLoadFinished will be a promise, resolved when
less has finished its initial processing. less.refresh and
less.modifyVars also return promises.
When you compile filename.less the compiled CSS code has been inject in a style tag with id less:filename, so to get the compilled CSS code you can also use:
less.pageLoadFinished.then(
function() {
console.log(document.getElementById('less:filename').innerHTML);
}
);
Notice that the last example also applies the compiled CSS code on the page.
--end update
I expected that running something such as the following was possible:
<link rel="stylesheet/less" type="text/css" href="important.less">
<script src="less-1.7.3.js" type="text/javascript"></script>
<script>
css = less.tree.toCSS();
console.log(css);
</script>
unfortunately this does not work, but you can use the following code to get what you want:
<script src="less-1.7.3.js" type="text/javascript"></script>
<script>
var lessCode = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
lessCode = xmlhttp.responseText;
new(less.Parser)().parse(lessCode, function (e, tree) {
document.getElementById('lesscode').innerHTML = tree.toCSS().replace(/\n/g,"<br>");
});
}
};
xmlhttp.open("GET","important.less",true);
xmlhttp.send();
</script>
With in the body section of your HTML:
<div id="lesscode"></div>
See also: Combining two .less files in one and How to open a local disk file with Javascript?
I just use Chrome's Inspect Element.
Right click on the element CSS you are looking for, Right click and choose Inspect element. On the right you will find the compiled CSS in Styles. Hope it helps
You have two options to do this, Internet Explorer or Firefox.
Let's start with Firefox. If you install the web developer toolbar, you get a menu option that's labelled CSS. Clicking on this gives you a few options and if you choose View CSS, you are taken to a new tab that shows you all of the styles for the page, grouped by their location and you should see a section with the CSS that has been generated by LESS and dynamically applied to the elements.
IE also has a Web Developer option and if you use the toolbar to inspect an element, you can then use the short cut 'Ctrl + T' which will bring up the page source with the computed styles.
The Firefox solution is better, as you can see exactly which styles have been provided by LESS whereas IE just lumps it all together.
There is a third option, and that is to compile the CSS server side!