Passing ejs parameters to stylus file - ejs

I am looking to pass a parameter to my Stylus file when it is being rendered. So for example in my app.js file I have:
app.get('/myPage', function(req, res) {res.render('myPageTemplate', { title:
'MyPageTitle' , myColor: '#E3D'});});
app.get('/myPage2', function(req, res) {res.render('myPageTemplate', { title:
'MyPage2Title' , myColor: '#0FF'});});
Obviously I can access these parameters in my ejs files e.g.
<title><%= title%></title>
In my Stylus file I would like to be able to do something like:
div{
background-color: <%=myColor%>;
}
Is this possible or am I going about this the wrong way?
Thanks for your help!

This is really a bad idea as most of the reverse proxies (if you are using one like cloudflare) cache your css and also it sets the Cache-Control headers so that browsers can cache it. So you will not get your desired behaviour.
Instead doing what you are doing now, you can create multiple css classes and add those classes to your div in .ejs file based on conditions.

Related

How do I load an ejs template file into my HTML?

I am using EJS in the browser (not on the server).
I have some ejs that I would like to use in multiple pages, so I want to put that in its own file, say table.ejs.
Is there a way I can include it in my HTML such that it is immediately accessible to my javascript after onload?
I was thinking something like:
<script id="table-ejs" type="text/ejs" src="ejs/table.ejs"></script>
then in my javascript:
ejs.render(document.querySelector('#table-ejs').???, data)
Is this possible?
I could use the Fetch API to retrieve the ejs file but then I would need to rewrite a lot of code to make it async. I was wondering if I could avoid that.
Well,
place all your ejs-files within a file "views" - within your views you can create another file "partials" - in this file you place your header and footer.ejs.
Within, lets say, your home.ejs you have to include the following code:
<%- include('partials/header'); -%>
// the rest of your code
<%- include('partials/footer'); -%>
You can find more here: https://ejs.co/#docs

eliminate inline <script> in file generated by doxygen

A proposed change to the Content Security Policy (CSP) of our web server to disallow inline script
is causing a problem with the documentation generated by doxygen. Specifically, the problem occurs
in the generated index.html file, and the following lines:
<!-- Generated by Doxygen 1.8.15 -->
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* #license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',false,false,'search.php','Search');
})
/* #license-end */</script>
If the initMenu() code is put into a separate file that is just included like other JavaScript files, everything
works just fine. Is there a doxygen option to put all JavaScript into files rather that inline? We can
post process the generated file to do this, but may not know when the "pattern" of this code may
change due to updates in doxygen itself. And we may not know if using additional doxygen features will result in other inline JavaScript.
Any suggestions would be welcome.
Thank you
Fritz Sieker
First off Content Security Policy is useful but far from being an absolute authority. There are other completely useless headers such as those that block referrers based on "privacy".
Secondly there is no such thing as "text/javascript", perhaps they meant application/javascript?
If you're using good (though very non-common practices) you don't have any script elements in the body element (use defer="true" on script elements in the head). By doing that you'll better understand the structure of JavaScript and that in turn will help you become more proficient/capable/help more people/make more money/etc.
You can use document.getElementsByTagName('body')[0].getElementsByTagName('script') to find all the script elements in the body element that don't belong there.
If you do have script elements in the body element beforehand and moving them to the head element is not feasible right now you're likely going to have to work with inherent logic, in short those script elements will always be inserted in to the DOM in a specific and reasonably easily reproducible area of your code (like as the very last elements). In such a case you can find them via the following:
document.getElementsByTagName('body')[0].lastChild
document.getElementsByTagName('body')[0].lastChild.previousSibling
document.getElementsByTagName('body')[0].lastChild.previousSibling.previousSibling
Keep in mind that pressing Enter in your code to make it more readable will insert a textNode so you may want to append nodeName to those instances and look for "script":
console.log(document.getElementsByTagName('body')[0].lastChild.nodeName);
There is the DOM TreeWalker that might help you out here, subjective to the end result in your DOM. I don't know offhand if you can transverse all the elements in reverse (probably).
Once you know what you want to delete instead of making everything convoluted just send that object (or id) to the following:
function element_del(id)
{
if (typeof id=='string' && id_(id) && id_(id).parentNode.removeChild)
{
id_(id).parentNode.removeChild(id_(id));
}
else if (typeof id=='object' && typeof id.parentNode=='object') {id.parentNode.removeChild(id);}
}
//Example:
element_del(document.getElementsByTagName('body')[0].lastChild);
I hope this helps!

CSS from code? How to use CSS decoration directly from Vala?

How to use CSS customization directly from Vala? Not like in this example with file. Let's say I want the button to turn red by clicking on it, without using an external css file, as this action is too simple to create a css file with a single field.
I mean smth like this:
label.set_styleSheet("font-size: 17px;")
You still have to create a CssProvider, like in the code you linked to:
var screen = this.get_screen ();
var css_provider = new Gtk.CssProvider();
You can call load_from_data () instead of load_from_path () to load it from a string in memory instead of a file:
https://valadoc.org/gtk+-3.0/Gtk.CssProvider.load_from_data.html
css_provider.load_from_data(".my_class { font-size: 17px; }");
Gtk.StyleContext.add_provider_for_screen(screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER);
When the CSS provider has loaded the custom styles to be used, you can manipulate every Gtk+ widget with get_style_context ().
The style context has methods to add, remove and query a class, etc.
https://valadoc.org/gtk+-3.0/Gtk.StyleContext.html
label.get_style_context().add_class("my_class");
Since you only have to setup the style provider once, I don't think it is too much overhead.
For anyone who is reading this I have posted both examples with and without file to Git https://gitlab.com/gavr123456789/vala-css-examples/tree/master

How in Sails to access globals in assets?

I am using Sails JS and would like to access globals (sails.config.myGlobals) in my assets, currently in js files.
I would have hoped I there is a similar way like injecting in ejs files. But its not.
Any ideas? Do I have to do a Grunt task for that?
In your config folder create a config file for example MyConfig.js (name doesn't matter). Fill that config with something that you wanted like.
module.exports.myconfig = {
configA: 'this is config A'
}
Use that config in your controller, like.
showconfig: function(req, res){
res.view('viewname', {
config: sails.config.myconfig
});
}
Now in your EJS file that is called, by that example is viewName.ejs at views folder, you can use it like <% config.configA %>, and this is config A would be printed. Also if you want Front End js (in assets folder) able to read that value, just print it in script tag, like this.
<script>
global.configA = '<%= config.configA %>';
</script>
Or if you use front end framework library, it can be placed under some value, service, or factory, not making global variable dirty, so other JS are able to read that value.
I don't think this is possible with Sails.
However, what you can do is setting the variable in a ejs view file to access its value in your js asset file.
// someView.ejs
<script>
myGlobals = '<%= config.myGlobals %>';
</script>

What is the proper way to integrate dynamic content into the layout.ejs file in a Sails.JS application?

Say I wrote a blog app in Sails.js.
On every page in this app, there is a sidebar widget called "Recent Posts", where it lists the titles of the 5 most recent posts and clicking on them takes you to the post in question.
Because this sidebar widget is present on every page, it should be in layout.ejs. But, here we have a conflict - dynamic content is only supposed to be pulled from the database in the controller action for rendering a specific view.
This dynamic content isn't for a specific view, it's for the whole site (via layout.ejs).
By the conventions that I understand, I'd have to get that dynamic content data for the sidebar widget in every controller action that renders a view (otherwise I would get an undefined error when I attempt to call that local in my layout.ejs file).
Things I've tried / considered:
Load that dynamic content in every controller action that renders a view (this solution is very bad) and calling that dynamic content in layout.ejs as if it were a local for the specific view. This works fine, but goes against D.R.Y. principles and quite frankly is a pain in the ass to have to run the same query to the database in every controller action.
As per another similar stackoverflow question, create a new config (E.G. config/globals.js), load my dynamic content from my database into that config file as a variable, and then calling sails.config.globals.[variable_name] in my layout.ejs file. This also worked, since apparently config variables are available everywhere in the application -- but it 's a hacky solution that I'm not a fan of (the content I'm loading is simply the titles and slugs of 5 recent posts, not a "global config option", as the solution implies).
Run the query to get the dynamic content inside the .EJS file directly between some <% %> tags. I'm not sure if this would work, but even if it did, it goes against the separation of concerns MVC principle and I'd like to avoid doing this if at all possible (if it even works).
As per a lengthy IRC discussion # http://webchat.freenode.net/?channels=sailsjs, it was suggested to create a policy and map that policy to all my controllers. In that policy, query the database for the 5 most recent posts, and set them to the req.recentposts. The problem with this solution is that, while the recent posts data will be passed to every controller, I still have to pass that req.recentposts data to my view -- making it so I still have to modify every single res.view({}) in every action. I don't have to have the database query in every action, which is good, but I still have to add a line of code to every action that renders a view... this isn't D.R.Y. and I'm looking for a better solution.
So, what is the proper solution, without needing to load that dynamic content in every controller action (a solution that adheres to D.R.Y. is what I'm lookng for), to get some dynamic content available to my layout.ejs file?
In folder /config you should create a file express.js and add something like that:
module.exports.express = {
customMiddleware: function(app){
app.use(function(req, res, next){
// or whatever query you need
Posts.find().limit(5).exec(function(err, posts){
res.locals.recentPosts = posts;
// remember about next()
next();
});
});
}
}
Then just make some simple loop in your view:
<% for(var i=0; i<recentPosts.length; i++) { %>
<% recentPosts[i].title %>
<% } %>
Here are some links to proper places in documentation:
https://github.com/balderdashy/sails-docs/blob/0.9/reference/Configuration.md#express
and
https://github.com/balderdashy/sails-docs/blob/0.9/reference/Response.md#reslocals
I found out another way to do this. What I did was to create a service that could render .ejs files to plain html by simply taking advantage of the ejs library already in sails. This service could either be invoked by the controller, or even passed as a function in the locals, and executed from within the .ejs. The service called TopNavBarService would look like:
var ejs = require('ejs');
exports.render = function() {
/* database finds goes here */
var userInfo = {
'username' : 'Kallehopp',
'real_name' : 'Kalle Hoppson'
};
var html = null;
ejs.renderFile('./views/topNavBar.ejs', {'locals':userInfo}, function(err, result) { html = result; });
return html;
}
In the constroller it could look like:
module.exports = {
testAction: function (req, res) {
return res.view('testView', {
renderNavbar: TopNavBarService.render // service function as a local!
});
}
};
This way you can create your customized ejs-helper that could even take arguments (although not shown here). When invoked, the helper could access the database and render a part of the html.
<div>
<%- renderNavbar() %>
</div>