Express, check if a template exists - node.js

Is there a way I can tell if a given template exists in express? Basically I want to create specific and fallback templates but don't want to contain that logic in the template itself.
if( res.templateExists( 'specific_page' ) ) {
res.render( 'specific_page' );
} else {
res.render( 'generic_page' );
}
The specific_page name is generatead at runtime based on the users device, language, etc.
NOTE: I don't need to know how to do string localization within a template, that I already have. I'm looking for cases where the entire layout/template changes.

You could use this:
res.render('specific_page', function(err, html) {
if (err) {
if (err.message.indexOf('Failed to lookup view') !== -1) {
return res.render('generic_page');
}
throw err;
}
res.send(html);
});
This will distinguish between an error thrown because the template couldn't be found (in which case it will render generic_page instead), and any other errors that might occur (which are re-thrown). It's not entirely stable because it relies on the error message that's being thrown, but I don't think there's any other way of determining the type of error.

Related

Svelte reactive statement with a variable fron onMount

I'm trying to style the currently active tab of my web project with the class "active". To target my tab elements I am using
onMount(() => {
const links = document.querySelectorAll(".topnav a");
});
I am then using a reactive statement to style the appropriate element like this
$: {
links.forEach((link) => {
if (link.getAttribute("id") === $page.url.pathname) {
link.classList.add("active");
} else {
link.classList.remove("active");
}
});
}
However, I have no way of sharing the links variable to my reactive statement. I also tried putting document.querySelectorAll inside my reactive statement (not using onMount at all), which worked flawlessly until i reloaded the page. What is the conventional approach to this?
You need to declare the variable outside of onMount so it is in scope of the reactive statement. E.g.
let links = null;
onMount(() => {
links = ...;
);
$: if (links != null) {
links.forEach((link) => {
});
Using document.querySelectorAll is not idiomatic Svelte.
Changing class (or other attributes) use the template syntax:
<a class:active={link.id === $page.url.pathname}>
{link.label}
</a>
If you really need access to the DOM api's Svelte has bind:this or action to get access to specific elements.

How to get entity from the argument and create if condition in Dialogflow Inline editor for fulfilment

I am completely new to Dialogflow and nodejs. I need to get the entity value from the argument to the function (agent) and apply if the condition on that. How can I achieve this?
I am trying below but every time I get else condition become true.
I have created an entity named about_member.
function about_member_handeller(agent)
{
if(agent.about_member=="Tarun")
{
agent.add('Yes Tarun');
}
else
{
agent.add("No tarun");
}
}
Please help.
In such cases, you may use console.log to help unleash your black box, like below:
function about_member_handeller(agent) {
console.log(JSON.stringify(agent, null, 2));
if(agent.about_member=="Tarun") {
agent.add('Yes Tarun');
}
else {
agent.add("No tarun");
}
}
JSON.stringfy() will serialize your json object into string and console.log will print the same on the stdOut. So once you run your code this will print the object structure for agent and after which you will know on how to access about_member. Because in the above code it's obvious that you are expecting about_member to be a string, but this code will let you know on the actual data in it and how to compare it.
To get the parameter you can use the following;
const valueOfParam = agent.parameters["parameterName"];

Validate collection elements in groovy

I have a List<File> where I would like to ensure that each File element is a directory, and if it is not, throw an exception.
In Java I would do:
List<File> possibleDirs;
...
for (File possibleDir : possibleDirs) {
if (!possibleDir.isDirectory()) throw new Exception();
...
}
but I am wondering if there is a better way to do this in groovy
I am wondering if there is a better way to do this in groovy
What you have there is fine. You could use some Groovy-isms like using a Closure for iterating:
possibleDirs.each { file ->
if(!file.isDirectory()) {
// throw exception...
}
}
Or...
def allAreDirs = possibleDirs.every { file ->
file.isDirectory()
}
if(!allAreDirs) {
// throw exception...
}
I don't think either of those is really any better than what you have. An argument against the every approach is that it has to visit every file where the previous approach and the approach you described bail out as soon as you know there is a problem.
EDIT:
I suppose you could also do something like:
if(possibleDirs.find { !it.isDirectory() }) {
// throw exception...
}

Checking if control exists throws an error

Really what I am after is a way to check if the control exists without throwing an error.
The code should look something like this:
Control myControl = UIMap.MyMainWindow;
if (!myControl.Exists)
{
//Do something here
}
The problem is that the control throws an error because it is invalid if it doesn't exist, essentially making the exists property useless.
What is the solution?
In this case I am using the tryfind method.
Like this:
HtmlDiv list = new HtmlDiv(Window.GetWebtop());
list.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
list.SearchProperties.Add(HtmlDiv.PropertyNames.InnerText, "Processing search", PropertyExpressionOperator.Contains);
if (list.TryFind())
{
//DO Something
}
I am re-posting the comment kida gave as a answer, because I think its the best solution.
Control myControl = UIMap.MyMainWindow;
if (!myControl.FindMatchingControls().Count == 0)
{
//Do something here
}
The FindMatchingControls().Count is much faster then the Try Catch or the TryFind. Since it does not wait for SearchTimeoutto check if the element is now there. Default it waits 30 seconds for the element to not be there, but I like my tests to fail fast.
Alternatively its possible to lower the Playback.PlaybackSettings.SearchTimeout before the Catch or TryFind and restore it afterwards, but this is unnecessary code if you ask me.
You can do one of two things: Wrap your code in a try-catch block so the exception will be swallowed:
try
{
if (!myControl.Exists)
{
// Do something here.
}
}
catch (System.Exception ex)
{
}
Or, you could add more conditions:
if (!myControl.Exists)
{
// Do something here.
}
else if (myControlExists)
{
// Do something else.
}
else
{
// If the others don't qualify
// (for example, if the object is null), this will be executed.
}
Personally, I like the catch block, because if I expect the control to be there as part of my test, I can Assert.Fail(ex.ToString()); to stop the test right there and log the error message for use in bug reporting.
If you are sure that control will exist or enabled after some time you can use WaitForControlExist() or WaitForControlEnabled() methods with a default timeout or specified timeout.
I have a situation like this and I am looping until the control is available :
bool isSaveButtonExist = uISaveButton.WaitForControlEnabled();
while (!isSaveButtonExist )
{
try
{
uISaveButton.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
uISaveButton.SetFocus(); // setting focus for the save button if found
isSaveButtonExist = uISaveButton.WaitForControlExist(100);
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message); // exception for every set focus message if the control not exist
}
}
// do something with found save button
// Click 'Save' button
Mouse.Click(uISaveButton, new Point(31, 37));
please refer to this link for more about these Methods:
Make playback wait methods

Cannot save in chrome Storage

I use the following code to load and save a value in chrome.storage:
$(document).ready(function()
{
$( "#filterPlus" ).click(function()
{
SaveSwitch("plus1","#filterPlus","plus1");
});
}
function SaveSwitch(propertyName, imageId, imageSrc)
{
chrome.storage.sync.get(propertyName, function (result) {
var oldValue = result.propertyName;
alert('GET:old='+oldValue);
if (oldValue==null)
{
oldValue=false;
}
var newValue=!oldValue;
chrome.storage.sync.set({propertyName: newValue}, function()
{
alert('SET:'+newValue);
});
});
}
When I run through this method, the first alert shows:GET:old=undefined, the second alert shows:SET:true just like expected. But when calling that method again with the same parameters the first alert AGAIN shows GET:old=undefined instead of GET:old=true which I expected.
It is the same behaviour when I use storage.local instead of storage.sync
"storage" is in the manifest's permissions. The JS is called from the options-page of my extension-
You're doing .get("plus1", ...) and then later doing .set({"propertyName": newValue}, ...). You are storing under the key "propertyName" but fetching the key "plus1", which has never been set.
Perhaps your misunderstanding is that keys in object literals are themselves literal (even when not quoted), rather than variable identifiers. In that case, you might benefit form reading How to use chrome.storage in a chrome extension using a variable's value as the key name?.

Resources