views:

287

answers:

5

Is there any "short" syntax for creating a struct in ColdFusion? I'd like to replace this verbose code:

<cfscript>
  ref = StructNew();
  ref.Template = "Label";
  ref.Language = "en";
  stcML = GetPrompts(ref);
</cfscript>

with something more like a JavaScript object:

<cfscript>
  stcML = GetPrompts({ Template: "Label", Language: "en" });
</cfscript>

Is there anything like this?

+1  A: 

In ColdFusion 8 and above you can create a structure like this:

ref={template="label", language="en"}
Sam Farmer
Kip, in CF8 you can use this syntax, as Sam says, but you can't use it in arguments to functions. In CF9, you can use the struct shorthand notation in arguments to functions; thus, your example above would work (with = instead of : though)
marc esher
+4  A: 

Coldfusion 8 has a struct literal notation:

<cfset objData = {
  Key1 = "Value1",
  Key2 = "Value2"
} />

However, there are a few strings attached:

Tomalak
so basically you can only use that short syntax for creating a 1-dimensional struct that is assigned to a variable. but you can't create one to pass to a function on the fly like i wanted. I guess that's more like a few *chains* attached...
Kip
sounds like this will be fixed in CF9 though!
Kip
Yeah, "chains" may be more accurate. I'd file CF8 struct literals under "one day late and one dollar short". Not sure why they rolled that out - in it's current form, it does not make much sense.
Tomalak
In ColdFusion 9, implicit structure and array notation is fixed. Nesting works, and you can create them "on the fly" as function or tag arguments: doFoo({foo="bar"}) or <cffile attributeCollection="#{action='read', ...}#"/>
Adam Tuttle
+1  A: 

In Railo 3 and above you create like this:

  • Struct: struct(a:1,b:2,c:3,d:"aaa")
  • Array: array(1,2,3,"aaa")
  • Query: query(col1:array(1.1,1.2,1,3),col2:array(2.1,2.2,2,3))
Peter Mattes
Aall those have been possible since Railo 1.
Peter Boughton
+1  A: 

You could use cfjson. Add the component to a scope you're using (e.g. the request scope):

<cfobject name="request.json" component="cfc.json">

and call it like:

<cfset aStructure = request.json.decode('{ Template: "Label", Language: "en" }')>
Loftx
+1  A: 

If your attempts to simplify struct syntax in CF8 run into nesting and/or inline deficiencies you can use this deceptively simple function:

<cfscript>
    function nStruct(){
     return arguments;
    }
</cfscript>

You can then use this syntax:

<cfdump var="#nStruct(
    a=1,
    b=nStruct(
     c=2,d=3
    )
)#" />
Raspin