ColdFusion - Cheatsheet
文章目录

ColdFusion xmlParse()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<cfscript>
arData = xmlParse(form.data);
</cfscript>


<table class="table table-bordered table-condensed table-datasubset">
<thead>
<tr class="bg-success">
<cfloop index="i" array="#arData.data.xmlchildren[1].xmlchildren#">
<th>#i.xmlname#</th>
</cfloop>
</tr>
</thead>
<tbody>
<cfloop index="i" array="#arData.data.xmlchildren#">
<tr>
<cfloop index="j" array="#i.xmlchildren#">
<td>#j.xmltext#</td>
</cfloop>
</tr>
</cfloop>
</tbody>
</table>

首先要求 XML 代码最外层必须被一个 root tag 包围, 否则会报以下错误:

1
The markup in the document following the root element must be well-formed.

对于下面的 XML

1
2
3
4
5
6
7
8
9
10
11
12
<data>
<details>
<location>IS Services (SC) - Denver, CO, USA</location>
<case_id>150</case_id>
<case_date>2015-03-14T00:00:00</case_date>
</details>
<details>
<location>IS Services (SC) - Denver, CO, USA</location>
<case_id>150</case_id>
<case_date>2015-03-14T00:00:00</case_date>
</details>
</data>

首先获得 data 下面的 details, 然后循环获取 details 下对应的 tag

注意如果使用 SQL Server 返回的 XML 需要在头尾加一个 <data>标签

Store Procedure

CF 端代码

1
2
3
4
5
6
7
8
9
10
11
12
<cfstoredproc procedure="dbo.PCC_Item_Compliance_Assess" datasource="#request.companyEHS_ODBC#">
<cfprocparam cfsqltype="cf_sql_varchar" value="#variables.maxItems#" />
<cfprocparam cfsqltype="cf_sql_varchar" value="#variables.businessID#" />
<cfprocparam cfsqltype="cf_sql_varchar" value="#variables.entityID#" />
<cfprocparam cfsqltype="cf_sql_varchar" value="#variables.itemID#" />

current options are REACH or RoHS --->
<cfprocparam cfsqltype="cf_sql_varchar" value="REACH,RoHS" />
<cfprocparam cfsqltype="cf_sql_varchar" value="#1#" />
<cfprocresult name="qResults">

</cfstoredproc>

最重要的就是 cfprocresult 这东西, 返回之后将其 dump 出来

就可以看到存储过程最后一次 select

createObject

Function syntax

1
CreateObject(type, component-name)

Parameters

  1. type

    Type of object to create.

    • com
    • corba
    • java
    • component
    • webservice
  2. component-name

    The CFC name; corresponds to the name of the file that defines the component; for example, use engineComp to specify the component defined in the engineComp.cfc file

Usage

1
2
3
4
5
6
7
8
9
<b>Server's Local Time:</b>
<cfscript> tellTimeCFC=CreateObject("component","appResources.components.tellTime");
tellTimeCFC.getLocalTime();
</cfscript>
<br>
<b>Calculated UTC Time:</b>
<cfscript>
tellTimeCFC.getUTCTime();
</cfscript>

Example

注意路径使用点来分割

1
objChart = CreateObject("component", "developer.emreyucel.area51.library.cfc.chartdirectordirector").init();

这里访问的是根目录下面的

1
/developer/emreyucel/area51/library/cfc/chartdirectordirector.cfc

ColdFusion: 得到当前服务器目录

Get current directory in server

1
fullpath = getDirectoryFromPath(getCurrentTemplatePath())

assuming that you are on Windows, and your fullpath looks something like c:\inetpub\site\dir, you can use this:

1
thisFolder = listlast(fullpath, "\/")

Ternary Expression 三元表达式

1
2
3
4
5
6
<cfscript>
variables.a = (5>4)?True:False;
</cfscript>
<cfoutput>
#a#
</cfoutput>

Coldfusion 日期相关

上周最后一天

1
##DateFormat(DATE - DayOfWeek(DATE) + 1) />#

DateFormat

1
2
dateformat(date,"d -mmm -yyyy")
DateFormat("date" [, "mask" ])
  • mask

Characters that show how ColdFusion displays a date:

  • d: Day of the month as digits; no leading zero for single -digit days.
  • dd: Day of the month as digits; leading zero for single -digit days.
  • ddd: Day of the week as a three -letter abbreviation.
  • dddd: Day of the week as its full name.
  • m: Month as digits; no leading zero for single -digit months.
  • mm: Month as digits; leading zero for single -digit months.
  • mmm: Month as a three -letter abbreviation.
  • mmmm: Month as its full name.
  • yy: Year as last two digits; leading zero for years less than 10.
  • yyyy: Year represented by four digits.
  • gg: Period/era string. Ignored. Reserved. The following masks tell how to format the full date and cannot be combined with other masks:
  • short: equivalent to m/d/y
  • medium: equivalent to mmm d, yyyy
  • long: equivalent to mmmm d, yyyy
  • full: equivalent to dddd, mmmm d, yyyy

输出日期和时间

日期时间一起:

1
##DateFormat(now(), 'd-mmm-yy')# #TimeFormat(now(), 'hh:mm tt')

日期差

1
DateDiff("datepart", "date1", "date2")

显示 date2 - date1 的结果

datepart:

1
2
3
4
5
6
7
8
9
10
11
12
String that specifies the units in which to count; for example yyyy requests a date difference in whole years.

yyyy: Years
q: Quarters
m: Months
y: Days of year (same as d)
d: Days
w: Weekdays (same as ww)
ww: Weeks
h: Hours
n: Minutes
s: Seconds

First day of quarter:

1
FirstDayOfQuarter = CreateDate(year, (quarter-1)*3 + 1, 1)

Last day of quarter:

1
LastDayOfQuarter = DateAdd("d", -1, DateAdd("m", 3, FirstDayOfQuarter))

Rereplace()

这里替换了不合法的文件名字符

1
2
<cfset variables['badFileNameCharset']='[\\~##%&*{}/:<>?|\"-]' />
<cfset variables['filename']=rereplace(qChemcialListName.listnameDIsplayed, variables['badFileNameCharset'],' ' , ' all') />

4 个参数:

  1. string
  2. regex
  3. substring
  4. scope: ‘one’ 或者 ‘all’

Query Loop in cfscript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
< cfscript >
// Loop over the records in the query.
for (intRow = 1; intRow LTE qPerson.RecordCount; intRow = (intRow + 1)) {

// Output the name some values. When doing so, access the
// query as if it were a structure of arrays and we want
// only get values from this row index.
WriteOutput(
qPerson["name"][intRow] & " is a " &
qPerson["sex"][intRow] & " that prefers doing " &
qPerson["preferred_category"][intRow] & " movies." &
"<br />"
);
} <
/cfscript >

Personal Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<cfquery name="q" datasource="#cc_odbc#">
declare @tbl as table (#meta.getTableDeclaration(rqColumns)#);

#meta.getDatasSQL(rqDataIDS , ck.ckpttableid, '@tbl' , rqColumns.cname.toArray())#

select
d.[#rvColumns#]
,s.orgname, s.location
from @tbl d
join meta_row r on d.did = r.did
join meta_scope s on r.scopeid = s.scopeid
</cfquery>

<cfscript>
if(form.casecount EQ 0) {
return writeoutput("there is not enough information to complete this request");
};

index = 1;
for(i=1; i LTE q.RecordCount; i++){

if(!toString(q[rvColumns][i]) == '')
continue;

writeoutput(toString(q[rvColumns][i]));

inputString = ('<data>' & toString(q[rvColumns][i]) & '</data>');

if(!isXML(inputString))
return writeoutput("there is not enough information to complete this request");

arData[index++] = xmlParse(inputString);
}
</cfscript>

注意获取 recordcount 的时候直接使用 queryname
之后再 loop 之中获取数据的时候是使用

1
queryName[columnName][RowName]

这样的形式

Prevent Output

两个方法

  • cfsilent 围起来

标签内的东西都不会输出(可以防止意外输出导致占用内存)

  • cfcontent 并且设置 reset=”yes”

清空在 cfcontent 标签之前的缓存

String

字符串连接(类 StringConcat 效果)

ColdFusion’s concatenation operator is &

1
<cfset teacherName = Firstname &" "& Lastname>

在 cfscript 中也是同样用法

1
2
3
<cfscript>
arData = xmlParse('<data>' & toString(form.data) & '</data>');
</cfscript>

另一种比较奇葩的方法

1
<cfset myStruct.concatendatedSring="#myStruct.string1##myStruct.string2#">

单引号字符串传到 cfquery 里面变为双引号

解决方法
中间加一个 Replace

1
2
<cfquery name="string_with_single_quote" datasource="schema_user" result="my_result"> #REReplace(string_variable,"''","'","ALL")#
</cfquery>

replace

Argument Reference

{: .table .table-striped}
| Name | Required | Default | Description |
| ———— | ———— |———— |
| String | Yes | | A string (or variable that contains one) within which to replace substring |
| substring1 | Yes |||
| substring2 | Yes |||
| scope | No || * one: Replace the first occurrence (default)*
all: Replace all occurrences | |

Usage in cfscript

1
2
3
4
5
getVal = replaceNoCase("ColdFUsion", "u", "a");
writeDump(getVal);

<cfset getVal=replaceNoCase("ColdFusiOn", "O" , "a" , "ALL" )>
<cfdump var="#getVal#">

String Split

1
<cfset a=TestString.Split("<br />")>

CF-Try/Catch

简单用法

嵌套用法, 注意内部捕捉之后不会被外部再次捕捉

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<cfscript>
try {
try {
a = b;
}
catch(any variable) {
// do something 1
} finally {

// do something 2
}
}
catch(any variable) {
// do something 3
} finally {
// do something 4

}
</cfscript>
1
2
3
4
5
6
<cftry>
<cfset a=URL.asd />
<cfcatch type="any">
<cfdump var="#cfcatch.tagcontext#" abort="true" expand="true">
</cfcatch>
</cftry>

NumberFormat

Syntax

1
2
NumberFormat(num, mask);
NumberFormat(123456789.99, ",")

Excel

cfspreadsheet

使用 CF 来 export excel 的时候使用到了这个 tag

Syntax

The tag syntax depends on the action attribute value:

注意 Read 和 Write 的参数有些不同, Write 的时候不需要 src 这样的参数

1
2
3
4
5
6
7
8
Read
<cfspreadsheet action="read" src="filepath" columns="range" columnnames="comma-delimited list" excludeHeaderRow="true | false" format="CSV|HTML" headerrow="row number" name="text" query="query name" rows="range" sheet="number" sheetname="text">

Update
<cfspreadsheet action="update" filename="filepath" format="csv" name="text" password="password" query="query name" sheetname="text">

Write
<cfspreadsheet action="write" filename="filepath" format="csv" name="text" overwrite="true | false" password="password" query="queryname" sheetname="text">

Example

新建一个 Excel 并写入数据

1
2
3
4
5
6
<cfset decSheetObj=SpreadsheetNew()>
<cfscript>
//Build Declaration Sheet
spreadsheetSetCellValue(variables.decSheetObj, 123, 56, 4);
</cfscript>
<cfspreadsheet action="write" filename="report.xls" sheetname="Declaration" name="decSheetObj" overwrite="true" />

SpreadsheetSetCellValue

Syntax

1
SpreadsheetSetCellValue(spreadsheetObj, value, row, column)

Example: Excel 输出

纯文本输出见附件

1
2
3
4
5
6
7
8
9
10
<cfscript>
decSheetObj = SpreadsheetNew();

[SomeCode……]

for(col=1; col<=arrayLen(rhColumns); col++) { spreadsheetSetCellValue(variables.decSheetObj, "123" , 1, 2); }
</cfscript> <!--- write and download--->
<cfspreadsheet action="write" filename="/report.xls" sheetname="Declaration" name="decSheetObj" overwrite="true" />
<cfheader name="Content-Disposition" value="attachment; filename=Report_#dateFormat(now(), 'yyyymmdd ')##timeFormat(now(), 'HHmmss')#.xls" />
<cfcontent file="/report.xls" type="application/vnd.ms-excel" deletefile="true" />

注意 cfcontent 的路径必须和上面 cfspreadsheet 写入的路径相同
不然会报找不到文件的错误

  • 上方代码测试有效
  • 运行正常的情况下会自动下载 Excel 并不会报错
  • 打开新窗口的情况下会弹出下载窗口

关于 Cell 风格的设置

http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-6747.html

Array Functions

Arrayfind

1
2
3
4
<cfscript>
writeDump(ArrayFind(["STRING","string"], "string"));
writeDump(ArrayFind(["STRING","string"], function(s) {if(compare(s, "string")==0) return true; return false;}));
</cfscript>

ArrayMap

这个比普通的循环方便多了

1
2
3
4
arrayMap([Array], function(item) {
……
return item.title;
})

Dump Message within condition

1
2
3
4
if(structKeyExists(url, "test")){
writeDump(variables.oPortalTranslator.translate('CAS:'));
abort;
}

Escape singlequote and doublequote

1
2
<!--- Here I have put two single quotes between Hari and s --->
<cfset variables.event = 'Hari''s first pen.' />

It will print as: Hari』s first pen.

1
2
<!--- Here I have put two single quotes around amnesia --->
<cfset variables.event = 'what you told the meaning of ''amnesia'' word?'/>

It will print as: what you told the meaning of 『amnesia』 word?

Escaping a double quote with in double quotes


HTML Encode/Decode

几种情况:

  1. Coldfusion 字符串, 用于 HTML 属性的值, 使用 encodeForHTML()
  2. Coldfusion 字符串, 用于 Excel 内容, 使用 decodeForHTML()

Query of Query

QoQ JOIN

首先 ColdFusion 不支持 JOIN

但是可以用取巧的方法:

1
2
SELECT *
FROM qTask, qScopeData

不过如果是 Left Join, Right Join 那样的需求就没办法了

报错

Error Executing Database Query.
Query Of Queries syntax error.
Encountered “. Incorrect GROUP BY column reference [].
Only simple column reference, and alias name are allowed.
Example: You can use alias to refer to a complex expression:
SELECT (a+b)/2 as x, count(*) FROM T GROUP BY x
The error occurred on line 69.

一般 QoQ 报错很有可能就是 SQL 格式出错, 找一下是否存在错误的用法改掉即可


listToArray

1
2
3
4
5
6
7
<h1>Demo for listToArray</h1>
<cfquery name="query" datasource="CC_TEST">
select top(3) * from ltbContact;
</cfquery>
<cfdump var="#query#" expand="false">
<cfset xAxisLabelsdata=listToArray(ValueList(query.CONTACT_LASTNAME,'|'),'|') />
<cfdump var="#xAxisLabelsdata#" expand="false">

Loop in Array

1
2
3
4
5
6
7
<h1>Demo For Loop in Array</h1>
<cfoutput>
<cfloop index="i" from="1" to="#ArrayLen(xAxisLabelsdata)#">
<!--- #i# - #xAxisLabelsdata[i]# <br> --->
<div width="30%" align="center">#i# - #xAxisLabelsdata[i]#</div>
</cfloop>
</cfoutput>

CFScript Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<cfscript>
data = { "FirstMetricGoal"=6.283185307179586476925286766559,
"FirstMetricRate"=3.1415926535897932384626433832795,
"SecondMetricGoal"=5.4365636569180904707205749427053,
"SecondMetricRate"=2.7182818284590452353602874713527
};

// Data for round Charts
data.roundChartAttributes = arrayNew(1);
for(i=1; i<=5 ; i=i+1)
{
data.roundChartAttributes[i] = structNew();
data.roundChartAttributes[i].currentValue = 0.5;
data.roundChartAttributes[i].yellowThreshold = 0.3;
data.roundChartAttributes[i].greenThreshold = 0.5;
data.roundChartAttributes[i].topScale = 1.0;
data.roundChartAttributes[i].allTransparent = "true";
data.roundChartAttributes[i].meterTitle = "Chart 1";
data.roundChartAttributes[i].boxHeight = "120";
data.roundChartAttributes[i].boxWidth = "120";
data.roundChartAttributes[i].radius = "50";
}

// Data for TriangleChart
data.arrTriangleChart = arrayNew(1);
// Format: Title | Position in Triangle (1 is the top) | Value to display | Color to display (Hex or string if available) | Text to display on helptext
data.arrTriangleChart[1] = "test1|1|1111|ffffff|test.";
data.arrTriangleChart[2] = "test2|2|222|ffffff|test22.";
data.arrTriangleChart[3] = "test3|3|333|ffffff|test33.";
data.arrTriangleChart[4] = "test3|4|333|ffffff|test33.";
data.arrTriangleChart[5] = "test3|5|333|ffffff|test33.";

// Data for Regulatory Training Completion
data.TrainCompletion_YTDElapsed="0.5";
data.TrainCompletion_YTD2014="0.8";

// Data for First Aid/NM/Concerns Rate
data.FA_NM_Concern_Rate="0.5";

// Data for Calendar Closure Rate
data.Calendar_Closure_Rate="0.8";

// Data for Incurred Costs
data.IncurredCosts_3YrAvg="2000";
data.IncurredCosts_2014="3000";

// Data for Finding Closure Rate
data.FindingClosureRate_PrioA="0.9";
data.FindingClosureRate_PrioB="0.9";
data.FindingClosureRate_PrioC="0.9";
data.FindingClosureRate_PrioD="0.9";

// Data for Finding Ratio
data.FindingRatio_Site="250";
data.FindingRatio_Crop="750";

</cfscript>

SerializeJSON

1
2
3
4
5
6
7
8
9
10
<cfparam name="IncludeSubOrgs" default="">
<!--- <cfheader name="Content-Type" value="application/json"> --->
<cfquery name="getSites" datasource="">
……
</cfquery>

<cfcontent reset="true" />
<cfoutput>
#SerializeJSON(getSites,true)#
</cfoutput>

Query of Query

1
<cfset subCategoryIDs=valueList(getsubcategories.subCategoryID)>
1
2
3
4
5
6
<cfquery name="getproducts">
SELECT *
FROM products
WHERE subCategoryID in (<cfqueryparam cfsqltype="cf_sql_integer" value="#subCategoryIDs#" list="true">)
ORDER BY RAND()
</cfquery>

Object

FindStructFindValue

1
2
3
4
5
6
7
8
9
<cfset sbiztemplist = "">
<cfset arrSearch = structfindvalue(structConcerns.IncidentsDetail,subbusiness,"all")>
<cfloop from="1" to="#arrayLen(arrSearch)#" index="arr">
<cfif arrSearch[arr].key eq "SubBusiness">
<cfif NOT listfindNoCase(sbiztemplist,arrSearch[arr].owner.Orgname,"|")>
<cfset sbiztemplist = listAppend(sbiztemplist,arrSearch[arr].owner.Orgname,"|")>
</cfif>
</cfif>
</cfloop>

Create a Excel and write data and download

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!--- Create a obj --->
<cfset decSheetObj=SpreadsheetNew()>

<!--- Write something --->
<cfscript>
spreadsheetSetCellValue(variables.decSheetObj, 123, 56, 4);
</cfscript>

<!--- Write to server --->
<cfspreadsheet action="write" filename="/report.xlsx" sheetname="Declaration" name="decSheetObj" overwrite="true" />

<!--- Download --->
<cfheader name="Content-Disposition" value="attachment; filename=Report_#dateFormat(now(), 'yyyymmdd ')##timeFormat(now(), 'HHmmss')#.xlsx" />
<cfcontent file="/report.xlsx" type="application/vnd.ms-excel" deletefile="true" />

ColdFusion to js

1
JSStringFormat(string)

Special Characters & Quotations

写成两个就行了

1
2
3
4
5
6
7
<cfset mystring="We all said ""Happy birthday to you.""">
<cfset mystring2='Then we said "How old are you now?"'>
<cfoutput>
#mystring#<br>
#mystring2#<br>
Here is a number sign: ##
</cfoutput>

Output:

1
2
3
We all said "Happy birthday to you." 
Then we said "How old are you now?"
Here is a number sign: #

List

在 HTML 中以

1
<cfset local.errorRowNum="123,321,124" />

的形式出现
一开始可以使用空值, 不需要 ListNew()这样的方法来新建 List, 之后再使用 ListAppend 来添加数据

ListAppend

一定要赋值给原来的 list, 单独调用一下函数不赋值是不会有效果的.

1
<cfset fruitlist = ListAppend(fruitList, "kiwi") />

Query to List: ValueList

将 Query 的 Result 转换为 List

1
valueList(column, [delimiter])

ListLen

获取 List 的长度, 在 Loop 的时候可能会用到

ListContains

1
2
3
ListContains(list, substring [, delimiters, includeEmptyValues ])

##ListContains(aList, "wo")#

Description

Determines the number of elements in a list. Integer; the number of elements in a list.

Function syntax

1
2
ListLen(list[, delimiters])
ListLen(list[, delimiters, includeEmptyValues])

Parameters

  • list

A list or a variable that contains one.

  • delimiters

A string or a variable that contains one. Characters that separate list elements. The default value is comma. If this parameter contains more than one character, ColdFusion processes each occurrence of each character as a delimiter.

  • includeEmptyValues

If includeEmptyValues is set to true, all empty values in the list will be considered when computing length. If set to false, the empty list elements are ignored.

Example

1
2
3
4
5
6
<cfset list="Partner,Response Date,Response Status" />
<cfloop from="1" to="#listLen(list)#" index="i">
<cfoutput>
listGetAt(list, i)
</cfoutput>
</cfloop>

Array

cfscript 中以

1
data=[0,0,0,0,0]

的形式出现

在 HTML 中以

1
2
3
4
5
6
7
8
9
<!--- 这句声明可以省略 --->
<cfset local.errorRowNum=arrayNew(1) />

<cfset local.errorRowNum=[1,2,3] />

<!--- 可以不按顺序赋值,但是使用未赋值的 index 可能报错 --->
<cfset local.errorRowNum[3]=arrayNew(1) />
<cfset local.errorRowNum[4]=arrayNew(1) />
<cfset local.errorRowNum[5]=arrayNew(1) />

以及

1
2
3
4
5
6
7
8
9
10
11
12
13
<cfset myarray=ArrayNew(1)>
<cfset myotherarray=ArrayNew(2)>
<cfset biggerarray=ArrayNew(3)>

<cfset biggerarray[1][1][1]=myarray>
<cfset biggerarray[1][1][1][10]=3>
<cfset biggerarray[2][1][1]=myotherarray>
<cfset biggerarray[2][1][1][4][2]="five deep">

<cfset biggestarray=ArrayNew(3)>
<cfset biggestarray[3][1][1]=biggerarray>
<cfset biggestarray[3][1][1][2][3][1]="This is complex">
<cfset myarray[3]="Can you see me">

的形式出现

几个特性

  • 效率比 Struct 要快

ArrayAppend

1
<cfset ArrayAppend(array_name, {value})>

放在 cfset 之中, 或者直接在 output 的时候用双井号调用
注意如果赋值的话就是 True or False

ListToArray

格式

1
listToArray("list", [delimiters])

Demo

1
2
3
4
5
6
7
<h1>Demo for listToArray</h1>
<cfquery name="query" datasource="CC_TEST">
select top(3) * from ltbContact;
</cfquery>
<cfdump var="#query#" expand="false">
<cfset xAxisLabelsdata=listToArray(ValueList(query.CONTACT_LASTNAME,'|'),'|') />
<cfdump var="#xAxisLabelsdata#" expand="false">

Query to Array: toArray()

1
qSites.siteid.toArray()

Debug Tips

由于 ColdFusion 是服务器端进行解析的, 一般不能够分步执行

一般使用的调试方法

  1. 使用 <cfabort> 来中断某段代码后方的所有代码

  2. 使用 <cfdump> 来进行查看, 甚至可以查看

    1. 可以直接 dump 出表单名来查看所有数据
  3. <cfscript> 中可以使用

1
WriteDump(vars)

来进行 dump


cfinclude & include in cfscript

用于文件引用

示例

1
2
3
4
5
6
7
<cfinclude template="myinclude.cfm">
<cfinclude template="……/myinclude.cfm">
<cfinclude template="/CFIDE/debug/myinclude.cfm">

<cfscript>
include "myinclude.cfm";
</cfscript>

ColdFusion Linebreak

tags: 换行, line break, coldfusion

Solution1&2

Use Chr(10) as \n
There is no support for \n or \r in CF. From the Live Docs

  • Chr(10) returns a linefeed character
  • Chr(13) returns a carriage return character
  • The two-character string Chr(13) & Chr(10) returns a Windows newline

Available if for normal string var output

1
<cfset someStr="This is line 1" & Chr(10) & "This is line 2" & Chr(10) & "This is line 3" />
1
2
<cfset NL=Chr(10) />
<cfset someStr="This is line 1 #NL# This is line 2#NL#This is line 3" />

Solution3

If you are into platform-independent development, you can do:

1
<cfset NL=CreateObject("java", "java.lang.System" ).getProperty("line.separator")>

For example, in your application.cfm/cfc or somewhere else high-level and use that.

Solution4

use

1
<*br*>

example:

1
2
"labelFontSize" = 7,
"labels" = ["Near Misses & Concern <*br*> Reports Logged", "First Aid Cases", "Other Recordable Cases", "Job Transfer or Restriction", "DAFW", "Fatalities"]

cfparam

1
<cfparam name="FORM.username" default="NULL"/>

使用方法

  • 可以直接写对应的 CF 变量
  • 可以使用表单提交过来的数据, 注意是获取表单里面对应 name 的数据
  • 可以使用 type 参数设定获取过来的类型, 如果不是对应类型就会报错?