Pug Conditional to Include All Subdirectories of a File Path - javascript

Simple problem that I must be overcomplicating...
I want to include a script file for any URL that contains /edit-post. Problem is, my editor URL will always be suffixed with a post title like this: /edit-post/some-post-title, therefore my Pug conditional never evaluates to true.
In other words, I'm looking for a conditional statement that will be true in both the following example conditions:
/edit-post/some-post-title
/edit-post/an-even-better-post-title
I have access to the path url variable already, and my conditionals are working fine when it's an exact match, so I'm trying to extend that to suffixed subdirectories. Here's what I'm starting with:
if path === '/edit-post'
//my script file
Is there maybe a way to include a regex expression or possibly some sort of "contains" statement in Pug?
I was thinking something like "/edit-post.*" or "edit-post[s/S]". Also got desperate and tried using .indexOf() which all you folks smarter than me will already know doesn't work in Pug templates!
Maybe there's a better way to achieve this altogether? Searched for hours. Tried a hundred combos. Pug's documentation is sparse. Plz send help! :)
Side note: I did find this neat little Pug/Jade conditional doc I've been using as a tester. Might be of use. http://learnjade.com/tour/conditionals/
Thanks in advance!

Actually I recommend You:
1) to rethink Your routing
2) create /layouts/admin for admin panel layout
3) create /admin/posts/edit view for edit purposes
But for Your question here is straightforward example:
router.get('/post/:slug/edit', (req, res) => {
Post
.findOne({slug: req.params.slug})
.exec((err, post) => {
res.render('post', {includeEdit: true, post});
});
});
Post is mongoose model
and in Your view file:
if includeEdit === true
include partials/edit

Related

Delete empty tags when testing with Jmeter

I am setting up some tests for Jmeter but i've encountered a problem which i've difficulty solving. In my JMS Point-to-Point i am using the following in the content section in JMeter content
i have a csv file with testdata for testing. All variables are written in this CSV with their value. for instance CoverageNr has a value of 1 then during testing Jmeter will use "< CoverageNr>1< /CovereageNr>" if it doesn't have a value it is empty: "< CoverageNr>< /CovereageNr>". And here we have the issue which i have. CoverageNr cannot be empty when used. What i want to achieve is when CoverageNr has no value, the tag "< CoverageNr>< /CovereageNr>" is not included in the test. I guess i have to make the entire tag configurable or use an if controller but so far to no avail. Can somebody give me some insights how to solve this problem?
I heard Groovy is a new Black so you can do this as follows:
Add JSR223 PreProcessor as a child of the JMS Point to Point sampler
Put the following code into the "Script" area:
import groovy.xml.XmlUtil
def content = sampler.getContent()
Node xml = new XmlParser().parseText(content)
cleanNode(xml)
def newContent = XmlUtil.serialize(xml)
sampler.setContent(newContent)
boolean cleanNode(Node node) {
node.attributes().with { a ->
a.findAll { !it.value }.each { a.remove(it.key) }
}
node.children().with { kids ->
kids.findAll { it instanceof Node ? !cleanNode(it) : false }
.each { kids.remove(it) }
}
node.attributes() || node.children() || node.text()
}
Demo:
Source: Remove null attributes and empty children from Node
Going forward I would recommend migrating to JSR223 Test Elements from Beanshell so in terms of performance it would be much better. Moreover Groovy has some nice sexy features, i.e. aforementioned XML processing so it will make your life easier
So i've solved the issue thanks to the other questions mentioned in the comment above and thanks to Dmitri T's answers for those questions. using a Beanshell Pre Processor did the trick with script being:
String data = sampler.getContent();
data = data.replaceAll("<CoverageN></CoverageN>","");
sampler.setContent(data);
Maybe it can be usefull for others.

React/Service worker unsure of reference

I am trying to set up a service worker for my react app using sw-precache ( https://github.com/GoogleChrome/sw-precache ) and am looking at some examples for reference. I of what a certain line of code means, and can't seem to find what it means googling. So looking at /!(*map*) in the context of -
module.exports = {
stripPrefix: 'build/',
staticFileGlobs: [
'build/*.html',
'build/manifest.json',
'build/static/**/!(*map*)' <-- here
],
dontCacheBustUrlsMatching: /\.\w{8}\./,
swFilePath: 'build/service-worker.js'
};
I am not sure what that does/means and am wondering if anyone could provide some clarity, I am not able to find a good reference googling. I am looking at https://github.com/jeffposnick/create-react-pwa/blob/c-r-pwa-0.6.0/sw-precache-config.js for reference. Thanks!
It just means that map files won't be included. So your map files for CSS and JS.
But actually it wouldn't include anything with the characters map in the filename or directory name.

i18next best practice

I've successfully implemented i18next, which by the way is a great library! Though I'm still in search for the "best practice". This is the setup I have right now, which in general I like:
var userLanguage = 'en'; // set at runtime
i18n.init({
lng : userLanguage,
shortcutFunction : 'defaultValue',
fallbackLng : false,
load : 'unspecific',
resGetPath : 'locales/__lng__/__ns__.json'
});
In the DOM I do stuff like this:
<span data-i18n="demo.myFirstExample">My first example</span>
And in JS I do stuff like this:
return i18n.t('demo.mySecondExample', 'My second example');
This means I maintain the English translation within the code itself. I do however maintain other languages using separate translation.json files, using i18next-parser:
gulp.task('i18next', function()
{
gulp.src('app/**')
.pipe(i18next({
locales : ['nl','de'],
output : '../locales'
}))
.pipe(gulp.dest('locales'));
});
It all works great. The only problem is that when I've set 'en' as the userLanguage, i18next insists on fetching the /locales/en/translation.json file, even though it doesn't contain any translations. To prevent a 404, I currently serve an empty json object {} in that file.
Is there a way to prevent loading the empty .json file at all?
Maybe I'm missing something here but couldn't you simply do this:
if (userLanguage != 'en') {
i18n.init({
lng : userLanguage,
shortcutFunction : 'defaultValue',
fallbackLng : false,
load : 'unspecific',
resGetPath : 'locales/__lng__/__ns__.json'
});
}
That way your script i18n wouldn't be initialized unless you actually needed the translation service.
i18next-parser author here, I will explain how I use i18next and hopefully it will help:
1/ I do not use defaultTranslation in the code. The reason is that it doesn't belong in the code. I understand the benefit of having the actual text but the code can get bloated quickly. The difficult part consists in defining intelligible translation keys. If you do that, you don't really need the defaultTranslation text anymore. The translation keys are self-explainatory.
2/ If you have a 404 on the /locales/en/translation.json, then probably that you don't have the file in your public directory or something similar. With gulp you can have multiple destination and do dest('locales').dest('public/locales') for instance.
3/ If there is no translation in the catalog, make sure you run the gulp task first. Regarding populating the catalog with the defaultTranslation you have, it is a tricky problem to solve with regexes. Think of this case <div data-i18n="key">Default <div>translation</div></div>. It needs to be able to parse the inner html and extract all the content. I just never took the time to implement it as I don't use it.
See http://i18next.com/pages/doc_init.html under "whitelist languages to be allowed on init" (can't fragment link on those docs...):
i18n.init({ lngWhitelist: ['de-DE', 'de', 'fr'] });
Only specified languages will be allowed to load.
That should solve your problem. Though I suppose a blacklist would be even better.

How to use g:message from Javascript

There are some messages coming from a Javascript file to a GSP page. How can I implement g:message in a Javascript page?
For example:
if ($('#name').val() == "") {
$('#nameStatus').show();
$('#nameStatus').html('<font color=red>Company Name can not be blank</font>');
return false;
Try this kind of syntax :
function foo() {
return "${message(code:'my.message.code')}";
}
If I understand correctly, you want to be able to use the output from g:message in your javascript.
There is a very helpful blog post which talks about how to use g:createLink in a similar way that you want, so you can easily adapt it to use g:message as well. Check out the post here, there is some useful info in the comments as well.
The idea is to create javascript objects in your GSP file; which should be defined before including your javascript file; and then just access those global objects in your js code.
Edit:
You might also be interested in the GSParse Plugin. I haven't tried it my self but I think it accomplishes what you are looking for as well.

Call a JavaScript function from C++

I have a CDHTMLDialog, with which I have 2 HTML pages and a .js file with a few fairly simple functions.
I would like to be able to call one of the JS functions from my program with a simple data type passed with it. e.g. MyFunc(int). Nothing needs to be returned.
I would appreciate any guidance on how I go about this,
thanks.
Edit: Thanks to CR for his answer, and everyone else who submitted there ideas too.
Something a little like this worked in the end (stripped a little error handling from it for clarity):
void callJavaScriptFunc(int Fruit)
{
HRESULT hRes;
CString FuncStr;
CString LangStr = "javascript";
VARIANT vEmpty = {0};
CComPtr<IHTMLDocument2> HTML2Doc;
CComPtr<IHTMLWindow2> HTML2Wind;
hRes = GetDHtmlDocument(&HTML2Doc);
hRes = HTML2Doc->get_parentWindow(&HTML2Wind);
if( Fruit > 0 )
{
FuncStr = "myFunc(808)"; // Javascript parameters can be used
hRes = HTML2Wind->execScript(FuncStr.AllocSysString(), LangStr.AllocSysString(), &vEmpty);
}
}
Easiest approach would be to use the execScript() method in the IHTMLWindow2 interface.
So you could get the IHTMLDocument2 interface from your CDHTMLDialog by calling GetDHtmlDocument, then get the parentWindow from IHTMLDocument2. The parent window will have the IHTMLWindow2 interface that supports execScript().
There might be an easier way to get the IHTMLWindow2 interface from your CDHTMLDialog but I'm used to working at a lower level.
the SpiderMonkey library can "Call a JavaScript function from C++", please refer to
http://egachine.berlios.de/embedding-sm-best-practice/ar01s02.html#id2464522
but in your case, maybe this is not the answer.
To give you a hint - javascript injection in server-side-technologies is usually performed through bulk-load at startup (GWT) or injected when the HTML is generated and served each post-back (ASP.NET).
The important point of both approaches is that they inject the javascript calls somewhere in the page (or in a separated .js file linked in the HTML in case of GWT) when generating the HTML page.
Even if you're on win development (looks like it since you're on MFCs) it might be the case that you have to insert your js method call in the HTML and then load (or reload if you wish to interact with the html from your MFC app) the HTML file in your CHTMLDialog.
I don't see any other way of achieving this (maybe I am just not aware of some suitable out-of-the-box functionality) other than editing your HTML and (re)loading it - which is pretty convenient and workable if you have to call your js method once off or just inject some kind of event-handling logic.
Might be a bit of a pain if you have to interact with the page from your MFC app. In this case you have to re-generate your HTML and reload it in your CHTMLDialog.
Either way you can simply have some kind of placeholder in your HTML file, look for that and replace with your javascript code, then load the page in your CHTMLDialog:
onclick="__my_Javascript_Call_HERE__"

Categories

Resources