I need to load and apply CSS at runtime in my Flex app. I know that the adobe docs say that you need to compile the CSS before loading it but I would like to find a work around.
I know that you can set individual styles like this:
cssStyle = new CSSStyleDeclaration();
cssStyle.setStyle("color", "<valid color>);
FlexGlobals.topLevelApplication.styleManager.setStyleDeclaration("Button", cssStyle, true);
I was planning on parsing a CSS file and appling each attribute as above.
I was wondering if:
Adobe had a CSS parser library that I could use
Someone else had a CSS parser that I could use
If I write my own CSS parser what I should watch out for
I know that the adobe flex.text.StyleSheet class has a CSS parser but I could not find a way to harness that. (Is there a way to get that source code?)
Edit: This solution does not work. All selectors that are taken out of the parser are converted to lowercase. This may work for your application but it will probably not...
I am leaving this answer here because it may help some people looking for a solution and warn others of the limitations of this method.
Although it was not intended for this it is possible to use the StyleSheet class to parse the CSS. I am currently investigating how robust this is currently but for the most part it appears to be working.
public function extractFromStyleSheet(css:String):void {
// Create a StyleSheet Object
var styleSheet:StyleSheet = new StyleSheet();
styleSheet.parseCSS(css);
// Iterate through the selector objects
var selectorNames:Array = styleSheet.styleNames;
for(var i:int=0; i<selectorNames.length; i++){
// Do something with each selector
trace("Selector: "+selelectorNames[i];
var properties:Object = styleSheet.getStyle(selectorNames[i]);
for (var property:String in properties){
// Do something with each property in the selector
trace("\t"+property+" -> "+properties[property]+"\n");
}
}
}
I had similar problem but more precisely i want the completely avoid the compilation because my application is wrapper by ActiveX used by a custom exe file and i let the software distributor to customize their skin.
In practice we put the <fx:Style> outside the application. To avoid low level parsing on the string we had transformed the Style Sheet in an XML:
<styles>
<namespace name="myNs" value="com.myComponent">
<declaration selector="myNS|Button#myselector:over #mysubselector">
color:#ffffff;
font-size:bold
</declaration>
... other styles
</styles>
Beside the security considerations about let the user know your components you can load the XML and create a CSSStydeclaration.
Splitting and parsing only the selector let you create a series of CSSCondition and CSSSelector to add to your CSSStyleDeclaration. To parse the selector we use a little loop which search "#",":" and "." and split the string mantaining the sequence of the found CSS conditions.
var selectors:Array = [];
// first selector
var conditions:Array = [
new CSSCondition(CSSConditionKind.ID, 'myselector');
new CSSCondition(CSSConditionKind.PSEUDO, 'over');
];
// here you have to find and expand the namespace
ancestor:CSSSelector = new CSSSelector('com.myComponent.Button', conditions);
selectors.push(selector);
// second selector
var conditions:Array = [
new CSSCondition(CSSConditionKind.ID, 'mysubselector');
];
selector:CSSSelector = new CSSSelector('', conditions, ancestor);
selectors.push(selector);
// Empty style declaration
new CSSStyleDeclaration(selectors, styleManager, false);
Then you can parse CSS properties by parseCSS() with the function created by #sixtyfootersdude, but using a fake selector:
var myCSS:String = "#fake " + "{" + cssTextReadedFromXML + "}";
var style:StyleSheet = new StyleSheet();
sheet.parseCSS(myCSS);
// here you have your parsed properties
var list:Object = sheet.getStyle('#fake');
Then you can add the properties to the CSSStyleDeclaration and apply them by the setStyle method and apply the declaration as in your example.
Less or more is how I've tryed to resolve this.
Related
Within the author it displays a breadcrumb, and I know you can modify its display to either some other static text or localisation, but I'm wondering if it's possible to dynamically show an attribute, or execute some other context-specific xpath dynamically.
As a test I can change the breadcrumb using the localisation editor variable ${i18n()}.
cc_config.xml
<elementRenderings platform="webapp">
<render element="num" as="${i18n(test)}" annotation="${i18n(test)}"/>
translation-cc.xml
<key value="test">
<comment></comment>
<val lang="en_US">Year</val>
"Year" is actually a num element.
However, trying any other variable, even 'more static' ones like ${cf} or ${tp} simply render the variable text literally, instead of evaluating it.
cc_config.xml
<elementRenderings platform="webapp">
<render element="paragraph" as="${xpath_eval(./#eId)}" annotation="${xpath_eval(./#eId)}"/>
<render element="p" as="${tp}" annotation="${tp}"/>
(paragraphs do have an eId attribute)
As you can see, I tried using annotation; but these tooltips also simply display the variable literally.
I also fiddled and tried a bunch of xpath stuff, like #eId/.#eId//#eId, but I think there's some restriction in using the Content Completion Configuration File with respect to editor variables.
So is the thinking right but I am doing something wrong, or is it not the right way but there is some other way to affect the breadcrumb? Maybe with the schema?
The element display names in cc_config.xml file do not support most of the editor variables. Most of them, like ${cf} (current file) and ${tp} (total number of pages) don't make sense to be used when rendering the name of an element.
The xpath_eval would make sense - the display name of an element may depend on its attributes (e.g. the #id attribute), it's index in the document (e.g. 'Section 3'), etc. We have a feature request registered for this case and I added your vote to it.
As a partial workaround you can use a JS API to compute the display name of the element based on the element original name and its attributes:
goog.events.listen(workspace, sync.api.Workspace.EventType.BEFORE_EDITOR_LOADED, function(e) {
e.options.elementNameEnhancer = function(elemName, attrs) {
var displayString = elemName;
var attr = attrs['id'];
if (attr) {
displayString += ' (#' + attr.attributeValue + ')';
}
return displayString;
};
});
If child template defined something in onCreated,
Template.test.onCreated(function() {
this.xxx = 'test';
});
And I want to access child context in parent. How can I do that?
You can use Session or ReactiveVar for this operation. But if you need to save it on the child template I think you could use:
var childView = Blaze.getView(currentTemplate.find('#your-child-theme-id'));
and then get template instance by:
var childTemplateInstance = childView._templateInstance;
and then
var myXXXvar = childTemplateInstance.xxx;
But this is a little bit dirty :/ I don't think there is a Meteor API for this particular use case. I think you should play with reactive vars or client only collections etc. I don't know exactly what you want to achieve.
I am a beginner with AngularJS and I have a little problem, I installed grunt-contrib-less to support less files instead css but now I have to declare all less styles that will be compiled into only one css file.
But my problem is normally when I'm using less, I write some code for a specific page, and here I have to write the style code for all pages. This is confusing and not really maintanable so is there a best practice to organize less styles?
I tought that there may be multiple solution:
Apply a class to body tag and change it with I don't know what
(controller, services or other)
(Import LESS file only for one page)
Generate multiple css file depending which style is compiled (but I can't do this because I can't configure grunt correctly)
Do this with DOM manipulation (but it don't find it beautifull because I think Angular must have a good way to solve that problem)
Could you explain me how to have different style for differents views ? I don't want to have the same style for all links in all views and without create hundreds classes I don't know how to do that.
Use directive
and add whatever variables/code/logic you want to add
HTML template(directive) of style can be added to your view and after compile you will get different ui for all your views
for reference read
angular directive
I solve my problem by adding specific class on body tag depending the route.
I put a variable in rootScope called 'pageStyle' with correspond to the classname that I want. This variable is updated automatically when route change (see run function). There is an event when the route change ($stateChangeSuccess or $routeChangeSuccess depending if you are using ngRoute or -angularui-routeur).
In my case i would like to add the name of the route but you can do it with the controller name or something else.
Here is an example
This is the routes :
angular
.module('frontApp', [])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider, $mdThemingProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: '../views/home.html',
controller: function ($scope) {
$scope.msg = 'Xavier';
}
})
.state('form', {
url: '/form',
templateUrl: '../views/form.html',
controller: 'FormCtrl'
});
}])
And in the run function you will see the event bound to adapt the class when route change :
.run(function($rootScope) {
$rootScope.pageStyle = '';
// Watch state and set controller name in pageStyle variable when state change
$rootScope.$on('$stateChangeSuccess', function(event, toState) {
event.preventDefault();
if (toState && toState.name && typeof toState.name === 'string'){
$rootScope.pageStyle = toState.name;
} else {
$rootScope.pageStyle = '';
}
});
});
Extra informations :
Note that the event called when route change is different if you are using ngroute. use "$routeChangeSuccess" if you use ngRoute and "$stateChangeSuccess" if you choose to use angular-ui-routeur
If you want to add the controller name instead the route name simply use the follow and replace 'ctrl' with you controller suffixe:
if (toState && toState.controller && typeof toState.controller !== 'function'){
$rootScope.pageStyle = toState.controller.toLowerCase().replace('ctrl','');
}
Hope it help someone else
I have multiple DIV elements on my page with the class "grid-item-container"
I want to make the background-color of each one different. I will set an array of 5 different colours that can be set.
There is a script available here that seems to do this: http://jsfiddle.net/VXG36/1/
$(document).ready(function() {
var randomColors = ["green","yellow","red","blue","orange","pink","cyan"];
$(".random").each(function(index) {
var len = randomColors.length;
var randomNum = Math.floor(Math.random()*len);
$(this).css("backgroundColor",randomColors[randomNum]);
//Removes color from array so it can't be used again
randomColors.splice(randomNum, 1);
});
});
I cannot however get it to run on my page. Is there something in this script that needs to be amended to make it Wordpress friendly?
Kind regards
Dave
You might wan't to wrap it in something like this:
jQuery(document).ready(function($) {
// Inside of this function, $() will work as an alias for jQuery()
// and other libraries also using $ will not be accessible under this shortcut
});
The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link. Read more about it in Codex here.
Also, change $(.random) to $(.grid-item-container), this targets the class of your div.
I got error message when trying to run existing meteor project.
$meteor
=> Started proxy.
=> Started MongoDB.
=> Errors prevented startup:
While building the application:
client/coinmx.html:169: TRIPLE template tag is not allowed in an HTML attribute
...title="Totals: {{{get...
^
In Meteor 0.8, it's possible to return a Javascript object which is directly rendered into HTML attributes versus earlier versions, where you had to render it yourself.
Old version:
<input name={{name}} title={{title}}>
helpers:
Template.foo.name = "fooName";
Template.foo.title = "fooTitle";
New version:
<input {{attributes}}>
helpers:
Template.foo.attributes = {
name: "fooName",
title: "fooTitle"
};
All of these can be functions, and reactive, etc. Because the object is rendered directly into attributes, there is no need for you to SafeString some manually rendered content as before. This is the recommended way to go if need to render HTML attributes.
See also the following for how conditional attributes work under this scheme:
https://github.com/meteor/meteor/wiki/Using-Blaze#conditional-attributes-with-no-value-eg-checked-selected
The error is pretty much explanatory: you cannot use {{{something}}} inside a HTML attribute, you need to use {{something}} instead. Depending on what the something is (it's not known from your question as you didn't provide the code), that's either all you need to do, or you can achieve similar functionality by returning new Handlebars.SafeString("result") from your helper instead of just "result". However, if you do, you need to be super sure that the thing you'll return won't break the HTML structure.
Hugo's answer above gave me the missing piece I needed for the same issue-- triple stashes in 0.8 no longer supported. Here is an example that hopefully helps.
Where you might have had {{{resolve}}} in your template, you would now do:
<template name='thing'>
<ol>
{{#each all}}
{{resolve}}
{{/each}}
</ol>
<template>
The helper code then makes use of Spacebars.SafeString which looks to be preferred with Blaze:
Template.thing.helpers({
all: function () {
return Things.find();
},
resolve: function () {
var result = "<li>";
for (var i = 0; i < this.arrayOfClassNames.length; ++i)
result += <'div class='" + this.arrayOfClassNames[i] + "'></div>";
result += "</li>";
return new Spacebars.SafeString(result);
}
});
The key here is to return the 'new Spacebars.SafeString(result)' to wrap your HTML (which must be well formed).