How to add assignment #{} statements in Razor Pages inside loop - razor-pages

For instance, I want to perform the following
#foreach (var item in new List<int>() {0,1,2}) {
#{
var assignedItem = item + 1;
}
<div>#item</div>
<div>#assignedItem</div>
}
But I get the error:
Unexpected "{" after "#" character. Once inside the body of a code block (#if {}, #{}, etc.) you do not need to use "#{" to switch to code.
How would I add an assignment or other code within the foreach loop?

Interesting, you can write normal code in addition to HTML in the code statements.
#foreach (var item in new List<int>() {0,1,2}) {
var assignedItem = item + 1;
<div>#item</div>
<div>#assignedItem</div>
}

Related

Revit API Duplicate View as Dependent Template Parameters are missing on the first Dependent View created

We are batch creating Views and Dependent Views (currently only ViewPlans) via the Revit API in Revit 2019, 2020, and 2022. We are seeing the following inconsistent results in all three Revit versions.
Below is a simplified code snippet. On many but not all groups of three Duplicate Views, some Shared Parameters that are set in the View Template are present in the parent view, and child duplicate views 'B' and 'C' but not child duplicate view 'A'.
using (var transactionGroup = new TransactionGroup(document, "Create views and set parameter values"))
{
transactionGroup.Start();
var sectors = new["A", "B", "C"];
var viewLookup = new Dictionary<string, ElementId>();
using (var makeViewsTransaction = new Transaction(document, "Create views"))
{
makeViewsTransaction.Start();
ViewPlan mainPlan = ViewPlan.Create(document, viewFamilyTypeId, levelId);
mainPlan.Name = "Plan_Name_Sector";
viewLookup.Add(mainPlan.Name, mainPlan.Id);
if (mainPlan.CanViewBeDuplicated(ViewDuplicateOption.AsDependent))
{
foreach (string sector in sectors)
{
string viewName = mainPlan.Name + "_" + sector;
var childPlanId = mainPlan.Duplicate(ViewDuplicateOption.AsDependent);
var childPlan = document.GetElement(childPlanId) as ViewPlan;
childPlan.Name = viewName;
viewLookup.Add(childPlan.Name, childPlan.Id);
}
}
makeViewsTransaction.Commit();
}
using (var editViewsTransaction = new Transaction(document, "Set view parameters"))
{
editViewsTransaction.Start();
foreach (var entry in viewLookup)
{
var view = document.GetElement(entry.Value) as Autodesk.Revit.DB.View;
if (paramSet.ScopeBoxId.IntegerValue != ActionBroker.EmptyElementId.IntegerValue)
{
view.get_Parameter(BuiltInParameter.VIEWER_VOLUME_OF_INTEREST_CROP).Set(scopeBoxId);
}
}
editViewsTransaction.Commit();
}
transactionGroup.Assimilate();
}
Screenshot of a result sample showing the missing parameter values.
Has anyone else experienced this?
It seems to me like a pretty straight-forward use of the Revit API, but perhaps the transaction group is introducing problems? I'm not sure what we could/should do differently to get more consistent results. Any suggestions?

Magento - How to pass value from template to js file?

I developed an extension where you can define a connection id for newsletter 2 go.
I need to pass this id to the script skin\frontend\base\default\fekete\Newsletter2Go\js\utils.js
Template:
My first approach was to pass it to the script by adding a get parameter to it.
{... Hint: I removed the rest code which is not relevant for this question ... }
(window,document,"script","skin/frontend/base/default/fekete/Newsletter2Go/js/utils.js?id=<?php echo $id ?>","n2g");
I checked if this worked like this:
alert(findGetParameter("id"));
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
But it alerts null.
How can I pass the id to the script, without having to move the whole script to the template?
I solved it by creating a new extension. I developed a controller and then just made a XHR Request to my route, which just returns the needed value.

Getting an error while saving JSON in to mongodb [duplicate]

How do I display the content of a JavaScript object in a string format like when we alert a variable?
The same formatted way I want to display an object.
Use native JSON.stringify method.
Works with nested objects and all major browsers support this method.
str = JSON.stringify(obj);
str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output.
console.log(str); // Logs output to dev tools console.
alert(str); // Displays output using window.alert()
Link to Mozilla API Reference and other examples.
obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)
Use a custom JSON.stringify replacer if you
encounter this Javascript error
"Uncaught TypeError: Converting circular structure to JSON"
If you want to print the object for debugging purposes, use the code:
var obj = {
prop1: 'prop1Value',
prop2: 'prop2Value',
child: {
childProp1: 'childProp1Value',
},
}
console.log(obj)
will display:
Note: you must only log the object. For example, this won't work:
console.log('My object : ' + obj)
Note ': You can also use a comma in the log method, then the first line of the output will be the string and after that, the object will be rendered:
console.log('My object: ', obj);
var output = '';
for (var property in object) {
output += property + ': ' + object[property]+'; ';
}
alert(output);
console.dir(object):
Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
Note that the console.dir() feature is non-standard. See MDN Web Docs
Try this:
console.log(JSON.stringify(obj))
This will print the stringify version of object. So instead of [object] as an output you will get the content of object.
Well, Firefox (thanks to #Bojangles for detailed information) has Object.toSource() method which prints objects as JSON and function(){}.
That's enough for most debugging purposes, I guess.
If you want to use alert, to print your object, you can do this:
alert("myObject is " + myObject.toSource());
It should print each property and its corresponding value in string format.
If you would like to see data in tabular format you can use:
console.table(obj);
Table can be sorted if you click on the table column.
You can also select what columns to show:
console.table(obj, ['firstName', 'lastName']);
You can find more information about console.table here
Function:
var print = function(o){
var str='';
for(var p in o){
if(typeof o[p] == 'string'){
str+= p + ': ' + o[p]+'; </br>';
}else{
str+= p + ': { </br>' + print(o[p]) + '}';
}
}
return str;
}
Usage:
var myObject = {
name: 'Wilson Page',
contact: {
email: 'wilson#hotmail.com',
tel: '123456789'
}
}
$('body').append( print(myObject) );
Example:
http://jsfiddle.net/WilsonPage/6eqMn/
In NodeJS you can print an object by using util.inspect(obj). Be sure to state the depth or you'll only have a shallow print of the object.
Simply use
JSON.stringify(obj)
Example
var args_string = JSON.stringify(obj);
console.log(args_string);
Or
alert(args_string);
Also, note in javascript functions are considered as objects.
As an extra note :
Actually you can assign new property like this and access it console.log or display it in alert
foo.moo = "stackoverflow";
console.log(foo.moo);
alert(foo.moo);
To print the full object with Node.js with colors as a bonus:
console.dir(object, {depth: null, colors: true})
Colors are of course optional, 'depth: null' will print the full object.
The options don't seem to be supported in browsers.
References:
https://developer.mozilla.org/en-US/docs/Web/API/Console/dir
https://nodejs.org/api/console.html#console_console_dir_obj_options
NB:
In these examples, yourObj defines the object you want to examine.
First off my least favorite yet most utilized way of displaying an object:
This is the defacto way of showing the contents of an object
console.log(yourObj)
will produce something like :
I think the best solution is to look through the Objects Keys, and then through the Objects Values if you really want to see what the object holds...
console.log(Object.keys(yourObj));
console.log(Object.values(yourObj));
It will output something like :
(pictured above: the keys/values stored in the object)
There is also this new option if you're using ECMAScript 2016 or newer:
Object.keys(yourObj).forEach(e => console.log(`key=${e} value=${yourObj[e]}`));
This will produce neat output :
The solution mentioned in a previous answer: console.log(yourObj) displays too many parameters and is not the most user friendly way to display the data you want. That is why I recommend logging keys and then values separately.
Next up :
console.table(yourObj)
Someone in an earlier comment suggested this one, however it never worked for me. If it does work for someone else on a different browser or something, then kudos! Ill still put the code here for reference!
Will output something like this to the console :
Here's a way to do it:
console.log("%o", obj);
Use this:
console.log('print object: ' + JSON.stringify(session));
As it was said before best and most simply way i found was
var getPrintObject=function(object)
{
return JSON.stringify(object);
}
(This has been added to my library at GitHub)
Reinventing the wheel here! None of these solutions worked for my situation. So, I quickly doctored up wilsonpage's answer. This one is not for printing to screen (via console, or textfield or whatever). It does work fine in those situations and works just fine as the OP requested, for alert. Many answers here do not address using alert as the OP requested. Anyhow, It is, however, formatted for data transport. This version seems to return a very similar result as toSource(). I've not tested against JSON.stringify, but I assume this is about the same thing. This version is more like a poly-fil so that you can use it in any environment. The result of this function is a valid Javascript object declaration.
I wouldn't doubt if something like this was already on SO somewhere, but it was just shorter to make it than to spend a while searching past answers. And since this question was my top hit on google when I started searching about this; I figured putting it here might help others.
Anyhow, the result from this function will be a string representation of your object, even if your object has embedded objects and arrays, and even if those objects or arrays have even further embedded objects and arrays. (I heard you like to drink? So, I pimped your car with a cooler. And then, I pimped your cooler with a cooler. So, your cooler can drink, while your being cool.)
Arrays are stored with [] instead of {} and thus dont have key/value pairs, just values. Like regular arrays. Therefore, they get created like arrays do.
Also, all string (including key names) are quoted, this is not necessary unless those strings have special characters (like a space or a slash). But, I didn't feel like detecting this just to remove some quotes that would otherwise still work fine.
This resulting string can then be used with eval or just dumping it into a var thru string manipulation. Thus, re-creating your object again, from text.
function ObjToSource(o){
if (!o) return 'null';
var k="",na=typeof(o.length)=="undefined"?1:0,str="";
for(var p in o){
if (na) k = "'"+p+ "':";
if (typeof o[p] == "string") str += k + "'" + o[p]+"',";
else if (typeof o[p] == "object") str += k + ObjToSource(o[p])+",";
else str += k + o[p] + ",";
}
if (na) return "{"+str.slice(0,-1)+"}";
else return "["+str.slice(0,-1)+"]";
}
Let me know if I messed it all up, works fine in my testing. Also, the only way I could think of to detect type array was to check for the presence of length. Because Javascript really stores arrays as objects, I cant actually check for type array (there is no such type!). If anyone else knows a better way, I would love to hear it. Because, if your object also has a property named length then this function will mistakenly treat it as an array.
EDIT: Added check for null valued objects. Thanks Brock Adams
EDIT: Below is the fixed function to be able to print infinitely recursive objects. This does not print the same as toSource from FF because toSource will print the infinite recursion one time, where as, this function will kill it immediately. This function runs slower than the one above, so I'm adding it here instead of editing the above function, as its only needed if you plan to pass objects that link back to themselves, somewhere.
const ObjToSource=(o)=> {
if (!o) return null;
let str="",na=0,k,p;
if (typeof(o) == "object") {
if (!ObjToSource.check) ObjToSource.check = new Array();
for (k=ObjToSource.check.length;na<k;na++) if (ObjToSource.check[na]==o) return '{}';
ObjToSource.check.push(o);
}
k="",na=typeof(o.length)=="undefined"?1:0;
for(p in o){
if (na) k = "'"+p+"':";
if (typeof o[p] == "string") str += k+"'"+o[p]+"',";
else if (typeof o[p] == "object") str += k+ObjToSource(o[p])+",";
else str += k+o[p]+",";
}
if (typeof(o) == "object") ObjToSource.check.pop();
if (na) return "{"+str.slice(0,-1)+"}";
else return "["+str.slice(0,-1)+"]";
}
Test:
var test1 = new Object();
test1.foo = 1;
test1.bar = 2;
var testobject = new Object();
testobject.run = 1;
testobject.fast = null;
testobject.loop = testobject;
testobject.dup = test1;
console.log(ObjToSource(testobject));
console.log(testobject.toSource());
Result:
{'run':1,'fast':null,'loop':{},'dup':{'foo':1,'bar':2}}
({run:1, fast:null, loop:{run:1, fast:null, loop:{}, dup:{foo:1, bar:2}}, dup:{foo:1, bar:2}})
NOTE: Trying to print document.body is a terrible example. For one, FF just prints an empty object string when using toSource. And when using the function above, FF crashes on SecurityError: The operation is insecure.. And Chrome will crash on Uncaught RangeError: Maximum call stack size exceeded. Clearly, document.body was not meant to be converted to string. Because its either too large, or against security policy to access certain properties. Unless, I messed something up here, do tell!
If you would like to print the object of its full length, can use
console.log(require('util').inspect(obj, {showHidden: false, depth: null})
If you want to print the object by converting it to the string then
console.log(JSON.stringify(obj));
I needed a way to recursively print the object, which pagewil's answer provided (Thanks!). I updated it a little bit to include a way to print up to a certain level, and to add spacing so that it is properly indented based on the current level that we are in so that it is more readable.
// Recursive print of object
var print = function( o, maxLevel, level ) {
if ( typeof level == "undefined" ) {
level = 0;
}
if ( typeof level == "undefined" ) {
maxLevel = 0;
}
var str = '';
// Remove this if you don't want the pre tag, but make sure to remove
// the close pre tag on the bottom as well
if ( level == 0 ) {
str = '<pre>';
}
var levelStr = '';
for ( var x = 0; x < level; x++ ) {
levelStr += ' ';
}
if ( maxLevel != 0 && level >= maxLevel ) {
str += levelStr + '...</br>';
return str;
}
for ( var p in o ) {
if ( typeof o[p] == 'string' ) {
str += levelStr +
p + ': ' + o[p] + ' </br>';
} else {
str += levelStr +
p + ': { </br>' + print( o[p], maxLevel, level + 1 ) + levelStr + '}</br>';
}
}
// Remove this if you don't want the pre tag, but make sure to remove
// the open pre tag on the top as well
if ( level == 0 ) {
str += '</pre>';
}
return str;
};
Usage:
var pagewilsObject = {
name: 'Wilson Page',
contact: {
email: 'wilson#hotmail.com',
tel: '123456789'
}
}
// Recursive of whole object
$('body').append( print(pagewilsObject) );
// Recursive of myObject up to 1 level, will only show name
// and that there is a contact object
$('body').append( print(pagewilsObject, 1) );
You can also use ES6 template literal concept to display the content of a JavaScript object in a string format.
alert(`${JSON.stringify(obj)}`);
const obj = {
"name" : "John Doe",
"habbits": "Nothing",
};
alert(`${JSON.stringify(obj)}`);
I always use console.log("object will be: ", obj, obj1).
this way I don't need to do the workaround with stringify with JSON.
All the properties of the object will be expanded nicely.
Another way of displaying objects within the console is with JSON.stringify. Checkout the below example:
var gandalf = {
"real name": "Gandalf",
"age (est)": 11000,
"race": "Maia",
"haveRetirementPlan": true,
"aliases": [
"Greyhame",
"Stormcrow",
"Mithrandir",
"Gandalf the Grey",
"Gandalf the White"
]
};
//to console log object, we cannot use console.log("Object gandalf: " + gandalf);
console.log("Object gandalf: ");
//this will show object gandalf ONLY in Google Chrome NOT in IE
console.log(gandalf);
//this will show object gandalf IN ALL BROWSERS!
console.log(JSON.stringify(gandalf));
//this will show object gandalf IN ALL BROWSERS! with beautiful indent
console.log(JSON.stringify(gandalf, null, 4));
Javascript Function
<script type="text/javascript">
function print_r(theObj){
if(theObj.constructor == Array || theObj.constructor == Object){
document.write("<ul>")
for(var p in theObj){
if(theObj[p].constructor == Array || theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
document.write("<ul>")
print_r(theObj[p]);
document.write("</ul>")
} else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
}
}
document.write("</ul>")
}
}
</script>
Printing Object
<script type="text/javascript">
print_r(JAVACRIPT_ARRAY_OR_OBJECT);
</script>
via print_r in Javascript
var list = function(object) {
for(var key in object) {
console.log(key);
}
}
where object is your object
or you can use this in chrome dev tools, "console" tab:
console.log(object);
Assume object obj = {0:'John', 1:'Foo', 2:'Bar'}
Print object's content
for (var i in obj){
console.log(obj[i], i);
}
Console output (Chrome DevTools) :
John 0
Foo 1
Bar 2
Hope that helps!
I prefer using console.table for getting clear object format, so imagine you have this object:
const obj = {name: 'Alireza', family: 'Dezfoolian', gender: 'male', netWorth: "$0"};
And you will you see a neat and readable table like this below:
Circular references solution
To make string without redundant information from object which contains duplicate references (references to same object in many places) including circular references, use JSON.stringify with replacer (presented in snippet) as follows
let s = JSON.stringify(obj, refReplacer(), 4);
function refReplacer() {
let m = new Map(), v= new Map(), init = null;
return function(field, value) {
let p= m.get(this) + (Array.isArray(this) ? `[${field}]` : '.' + field);
let isComplex= value===Object(value)
if (isComplex) m.set(value, p);
let pp = v.get(value)||'';
let path = p.replace(/undefined\.\.?/,'');
let val = pp ? `#REF:${pp[0]=='[' ? '$':'$.'}${pp}` : value;
!init ? (init=value) : (val===init ? val="#REF:$" : 0);
if(!pp && isComplex) v.set(value, path);
return val;
}
}
// ---------------
// TEST
// ---------------
// gen obj with duplicate references
let a = { a1: 1, a2: 2 };
let b = { b1: 3, b2: "4" };
let obj = { o1: { o2: a }, b, a }; // duplicate reference
a.a3 = [1,2,b]; // circular reference
b.b3 = a; // circular reference
let s = JSON.stringify(obj, refReplacer(), 4);
console.log(s);
alert(s);
This solution based on this (more info there) create JSONPath like path for each object value and if same object occurs twice (or more) it uses reference with this path to reference that object e.g. #REF:$.bar.arr[3].foo (where $ means main object) instead 'render' whole object (which is less redundant)
BONUS: inversion
function parseRefJSON(json) {
let objToPath = new Map();
let pathToObj = new Map();
let o = JSON.parse(json);
let traverse = (parent, field) => {
let obj = parent;
let path = '#REF:$';
if (field !== undefined) {
obj = parent[field];
path = objToPath.get(parent) + (Array.isArray(parent) ? `[${field}]` : `${field?'.'+field:''}`);
}
objToPath.set(obj, path);
pathToObj.set(path, obj);
let ref = pathToObj.get(obj);
if (ref) parent[field] = ref;
for (let f in obj) if (obj === Object(obj)) traverse(obj, f);
}
traverse(o);
return o;
}
// ------------
// TEST
// ------------
let s = `{
"o1": {
"o2": {
"a1": 1,
"a2": 2,
"a3": [
1,
2,
{
"b1": 3,
"b2": "4",
"b3": "#REF:$.o1.o2"
}
]
}
},
"b": "#REF:$.o1.o2.a3[2]",
"a": "#REF:$.o1.o2"
}`;
console.log('Open Chrome console to see nested fields');
let obj = parseRefJSON(s);
console.log(obj);
A little helper function I always use in my projects for simple, speedy debugging via the console.
Inspiration taken from Laravel.
/**
* #param variable mixed The var to log to the console
* #param varName string Optional, will appear as a label before the var
*/
function dd(variable, varName) {
var varNameOutput;
varName = varName || '';
varNameOutput = varName ? varName + ':' : '';
console.warn(varNameOutput, variable, ' (' + (typeof variable) + ')');
}
Usage
dd(123.55); outputs:
var obj = {field1: 'xyz', field2: 2016};
dd(obj, 'My Cool Obj');
The console.log() does a great job of debugging objects, but if you are looking to print the object to the page content, here's the simplest way that I've come up with to mimic the functionality of PHP's print_r(). A lot these other answers want to reinvent the wheel, but between JavaScript's JSON.stringify() and HTML's <pre> tag, you get exactly what you are looking for.
var obj = { name: 'The Name', contact: { email: 'thename#gmail.com', tel: '123456789' }};
$('body').append('<pre>'+JSON.stringify(obj, null, 4)+'</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
i used pagewil's print method, and it worked very nicely.
here is my slightly extended version with (sloppy) indents and distinct prop/ob delimiters:
var print = function(obj, delp, delo, ind){
delp = delp!=null ? delp : "\t"; // property delimeter
delo = delo!=null ? delo : "\n"; // object delimeter
ind = ind!=null ? ind : " "; // indent; ind+ind geometric addition not great for deep objects
var str='';
for(var prop in obj){
if(typeof obj[prop] == 'string' || typeof obj[prop] == 'number'){
var q = typeof obj[prop] == 'string' ? "" : ""; // make this "'" to quote strings
str += ind + prop + ': ' + q + obj[prop] + q + '; ' + delp;
}else{
str += ind + prop + ': {'+ delp + print(obj[prop],delp,delo,ind+ind) + ind + '}' + delo;
}
}
return str;
};

NodeJS for-loop unsuccessful at trimming urls that end in with numbers

I'm trying to take a group of Facebook Page urls and extract only the entity title of the page. Ie for 'https://www.facebook.com/BalanceSpaBoca' I'm looking only for 'BalanceSpaBoca.' This script works great for most of the sample data I'm using (the testFBurls array), printing only the trimmed string. For others, though, it prints both the trimmed string and the original string. It seems like all of the urls that get printed twice end with a string of numbers, but I'm not sure why that should make any difference in how the program runs.
var testFBurls = [
'http://www.facebook.com/pages/A-Yoga-Way/361702000576231',
'http://www.facebook.com/aztigurbansalon',
'https://www.facebook.com/pages/Azzurri-Salon-Spa/542579982495983',
'https://www.facebook.com/BalanceSpaBoca',
'https://www.facebook.com/BocaAmericanNailsandSpa',
'http://www.facebook.com/beachyogagirl',
'https://www.facebook.com/pages/Beauty-of-Wax/156355679240',
'http://www.facebook.com/beehivefitness.boca',
'https://www.facebook.com/pages/Believe-Day-Spa-Boutique/197615685896',
'https://www.facebook.com/photo.php?fbid=10151725966640897&set=a.10151725965355897.1073741828.197615685896&type=1&theater',
'http://facebook.com/pages/bigfoot-spa/1486364798260300',
'http://www.facebook.com/bloheartsyou',
'http://www.facebook.com/pages/The-Wellness-Center-Of-Boca-Raton/170371382995576',
'https://www.facebook.com/TherapyBodyBalanced',
'https://www.facebook.com/pages/BodyVital-Massage/177664492277158',
'https://www.facebook.com/bodyworkmall',
'https://www.facebook.com/pages/The-Bombay-Room-Yoga-Studio/148731658497764',
];
var possibleFBurlStarts = [
"https://www.facebook.com/",
"http://www.facebook.com/",
"https://www.facebook.com/pages/",
"http://www.facebook.com/pages/",
];
for (var count=0; count<testFBurls.length; count++){
var currentURL = testFBurls[count];
if (currentURL.indexOf(".com/photo") > -1) {
testFBurls.splice(i, 1);
i--;
}
for (var i=0; i < possibleFBurlStarts.length; i++){
var indexOfSubstring = currentURL.indexOf(possibleFBurlStarts[i]);
if (indexOfSubstring > -1) {
var res = currentURL.replace(possibleFBurlStarts[i], "");
}
}
if (count == testFBurls.length-1){
console.log(testFBurls);
}
}
Here's my console output
pages/A-Yoga-Way/361702000576231
A-Yoga-Way/361702000576231
aztigurbansalon
pages/Azzurri-Salon-Spa/542579982495983
Azzurri-Salon-Spa/542579982495983
BalanceSpaBoca
BocaAmericanNailsandSpa
beachyogagirl
pages/Beauty-of-Wax/156355679240
Beauty-of-Wax/156355679240
beehivefitness.boca
pages/Believe-Day-Spa-Boutique/197615685896
Believe-Day-Spa-Boutique/197615685896
bloheartsyou
pages/The-Wellness-Center-Of-Boca-Raton/170371382995576
The-Wellness-Center-Of-Boca-Raton/170371382995576
TherapyBodyBalanced
pages/BodyVital-Massage/177664492277158
BodyVital-Massage/177664492277158
bodyworkmall
pages/The-Bombay-Room-Yoga-Studio/148731658497764
The-Bombay-Room-Yoga-Studio/148731658497764
Notice that the first url is listed twice (first in its original form, and secondly in its truncated form), but then the second url (the third line in the output) is listed in truncated form alone. Any ideas what is causing this disparity? Only the truncated url should be printed.
You're modifying the array you're iterating through while you're iterating through it: testFBurls.splice(i, 1); which is typically a not-great thing to do. In any case, I think you should be able to accomplish your goal a lot easier with a simple regular expression:
for (var count=0; count<testFBurls.length; count++){
var matches = testFBurls[count].match(/^https?\:\/\/www\.facebook\.com\/(?:pages\/)?([^\/]+)/);
if (matches) {
console.log('found it:', matches[1]);
}
}

How can I transform a notes view to a html nested list?

I would like to re-use a notes view in a web browser, Therefor I need the notes view (with response documents hierarchy) represented in HTML as an unordered list (ul) with list items (li).
What SSJS code should I use to compute this list?
None.
If you can edit the view, set it to passthru HTML and add one column at the beginning and end with the list tags. Set them hidden from client.
Or bind it to a repeat control and have the Li tags inside with computed text bound to the view columns. No SsJS in both cases.
NotesViewEntry.getPosition(Char separator) gives a hierarchical output. For example with the separator defined as "." it will give 3 for the third top-level entry, 3.5 for the fifth child of the third top-level entry, 3.5.7 for the seventh child of the fifth child of the third top-level entry.
To elaborate on Stephan's second option, a Repeat Control doesn't care about the structure of the data it's retrieving. It's a handle to a collection, where each "row" is one element in that collection. So if you point it to a collection which is myView.getAllEntries(), each entry is a NotesViewEntry.
Combine the two and you have the level of the hierarchy, if you want to just use indentation. Alternatively, from a NotesViewEntry you can tell if there are children, so whether you need to make it another li or start another ul.
Alternatively, if you want to get more elaborate, look at how I traverse views to create a Dojo Tree Grid navigation in XPages Help Application http://www.openntf.org/internal/home.nsf/project.xsp?action=openDocument&name=XPages%20Help%20Application
not the most beautiful code. I hope it works;
function getList() {
var nav:NotesViewNavigator=database.getView("notesview").createViewNav();
var entry:NotesViewEntry=nav.getFirst();
if (entry!=null){
var countLevel:Integer = 0;
var curLevel:Integer;
var list="";
while (entry != null) {
var edoc:NotesDocument = entry.getDocument();
entryValue = entry.getColumnValues().elementAt(1).toString();
var col:NotesDocumentCollection = edoc.getResponses();
var gotResponse:String;
if (col.getCount()>0){
gotResponse ="1";
}
else{
gotResponse ="0";
}
curLevel = entry.getColumnIndentLevel();
if (curLevel<countLevel){
//no responses & no siblings
var difLevel=countLevel-curLevel;
list=list + "<li>"+entryValue+ "</li>"
var closure="";
for (var i=0;i<(difLevel);i++) {
closure=closure+"</ul></li>"
}
list=list+closure;
countLevel=curLevel;
}
if (curLevel==countLevel){
if(gotResponse=="1"){
//got responses;handle them first
list=list+"<li>";
list=list+entryValue;
list=list+"<ul>";
countLevel=curLevel+1;
}
else{
//must be sibling
list=list + "<li>"+entryValue+ "</li>"
}
}
var tmpentry:NotesViewEntry=nav.getNext(entry);
entry.recycle();
entry=tmpentry;
}
//final closure, last entry could be response doc
var closure = ""
for (var i = 0; i < (countLevel); i++) {
closure = closure + "</ul></li>";
}
list = list + closure;
return list;
} else {
return "No documents found";
}
}

Resources