Resolving variables inside a Coldfusion string

后端 未结 4 641
长情又很酷
长情又很酷 2021-01-14 00:28

My client has a database table of email bodies that get sent at certain times to customers. The text for the emails contains ColdFusion expressions like Dear #firstName# and

相关标签:
4条回答
  • 2021-01-14 01:13

    If the variable is in a structure from, something like a form post, then you can use "StructFind". It does exactly as you request. I ran into this issue when processing a form with dynamic inputs.

    Ex.

    StructFind(FORM, 'WhatYouNeed')
    
    0 讨论(0)
  • 2021-01-14 01:22

    What other languages often do that seems to work very well is just have some kind of token within your template that can be easily replaced by a regular expression. So you might have a template like:

    Dear {{name}}, Thanks for trying {{product_name}}.  Etc...
    

    And then you can simply:

    <cfset str = ReplaceNoCase(str, "{{name}}", name, "ALL") />
    

    And when you want to get fancier you could just write a method to wrap this:

    <cffunction name="fillInTemplate" access="public" returntype="string" output="false">
        <cfargument name="map" type="struct" required="true" />
        <cfargument name="template" type="string" required="true" />
    
        <cfset var str = arguments.template />
        <cfset var k = "" />
    
        <cfloop list="#StructKeyList(arguments.map)#" index="k">
            <cfset str = ReplaceNoCase(str, "{{#k#}}", arguments.map[k], "ALL") />
        </cfloop>
    
        <cfreturn str />
    </cffunction>
    

    And use it like so:

    <cfset map = { name : "John", product : "SpecialWidget" } />
    <cfset filledInTemplate = fillInTemplate(map, someTemplate) />
    
    0 讨论(0)
  • 2021-01-14 01:24

    Not sure you need rereplace, you could brute force it with a simple replace if you don't have too many fields to merge

    How about something like this (not tested)

    <cfset var BaseTemplate = "... lots of html with embedded tokens">
    
    <cfloop (on whatever)>
    
       <cfset LoopTemplate = replace(BaseTemplate, "#firstName#", myvarforFirstName, "All">
       <cfset LoopTemplate = replace(LoopTemplate, "#lastName#",  myvarforLastName, "All">
       <cfset LoopTemplate = replace(LoopTemplate, "#address#",   myvarforAddress, "All">
    
    </cfloop>
    

    Just treat the html block as a simple string.

    0 讨论(0)
  • 2021-01-14 01:34

    CF 7+: You may use regular expression, REReplace()?

    CF 9: use Virtual File System

    0 讨论(0)
提交回复
热议问题