independent from templating macros and styles and with minimal dependencies,
part of standard Scipio Freemarker API.
Generally CSS-framework-agnostic.
Intended as platform-agnostic (html, fo, etc.) though some individually are only applicable for specific platforms.
Automatically included at all times, for all themes, independently of theme markup override files.
- Macros expect to be called using named arguments, except where otherwise noted.
-
Functions in Freemarker only support positional arguments, but some Scipio functions support
an "args" argument as a map, which emulates named arguments. -
Default markup-producing macros are found in standard/htmlTemplate.ftl.
In general, utilities found in utilities.ftl should not contain their logic. -
Except where otherwise required (placeholder/abstract), it is generally not intended for the
declarations in this file to be overridden. Although possible to do from theme markup overrides, it is unsupported.
- Macros should almost never use "request" object directly – use setRequestVar/getRequestVar/other.
-
It's important that these macros remain generic (and that the include for these utilities remains
completely static) so that any macro or function here can easily be interchanged with a transform (Java class).
All Definitions:
addClassArg,
addClassArgDefault,
addClassArgDefaultExplicit,
addClassArgReplacing,
addExtLoginKey,
addParamDelimToUrl,
addParamsToStr,
addParamsToStrUrlEnc,
addParamsToUrl,
addStringToBoolStringVal,
appUrl,
attribSpecialVal,
camelCaseToDashLowerName,
clearVars,
combineClassArgs,
compileClassArg,
compileClassArgExplicit,
compiledClassAttribStr,
compiledClassAttribStrExplicit,
compileProgressSuccessAction,
concatMaps,
containsStyleName,
containsStyleNamePrefix,
contentAltUrl,
contentArgRender,
contentUrl,
copyMap,
copyObject,
elemAttribStr,
escapeEventMsg,
escapeFull,
escapeFullUrl,
escapeMsg,
escapePart,
escapeUrlParamDelims,
escapeVal,
evalAbsContainerSizeFactors,
evalToSimpleMap,
extractPrefixedStyleNamesWithInt,
extractVars,
formatDate,
formatDateTime,
formattedDate,
formattedDateTime,
formattedTime,
formatTime,
getAbsContainerSizeFactors,
getAllContainerSizes,
getAttribMapAllExcludes,
getClassArgPrefix,
getCurrentHeadingLevel,
getCurrentSectionLevel,
getDefaultHeadingLevel,
getDefaultScipioLibLocation,
getDefaultSectionLevel,
getEntityPropertyValue,
getFilteredAttribMap,
getHeadingElemSpecFromStyleStr,
getLabel,
getLastContainerSizes,
getMacroLibraryLocationStaticFromResources,
getPlainClassArgNames,
getPropertyMsg,
getPropertyMsgFromLocExpr,
getPropertyValue,
getRawWrappedForLang,
getRenderContextType,
getRenderPlatformType,
getRequestNextElemIndex,
getRequestStackAsList,
getRequestStackSize,
getRequestVar,
getScipioMacroDefaultArgs,
getStyleNamesByPrefix,
getTextLabelFromExpr,
globalsPutAll,
htmlContentString,
interpretRequestUri,
interpretStd,
interpretStdLoc,
isAttribSpecialVal,
isObjectType,
isRawScript,
isWrappedAsRaw,
joinStyleNames,
joinStyleNamesList,
limitStrValToItems,
localsPutAll,
makeAppUrl,
makeAttribMapFromArgMap,
makeContentCtxPrefixUrl,
makeContentUrl,
makePageUrl,
makeSectionsRenderer,
makeServerUrl,
mapKeys,
maskValueLeft,
maskValueRight,
mergeArgMaps,
mergeArgMapsBasic,
mergeArgMapsEx,
mergeArgMapsToLocals,
mergeArgMapsToLocalsBasic,
mergeAttribMaps,
objectAsScript,
pageUrl,
parseContainerSizesFromStyleStr,
popRequestStack,
printVars,
pushRequestStack,
raw,
rawLabel,
rawLabelNoSubst,
rawString,
readRequestStack,
removeStyleNames,
render,
renderTarget,
rewrapMap,
rewrapObject,
rewrapString,
runScript,
runService,
sanitizeMarkup,
saveCurrentContainerSizes,
saveCurrentContainerSizesFromStyleStr,
serverUrl,
setContextField,
setCurrentHeadingLevel,
setCurrentSectionLevel,
setGlobalContextField,
setLastRequestStack,
setRequestAttribute,
setRequestVar,
setVars,
splitStrParams,
splitStyleNames,
splitStyleNamesToSet,
stripParamStrFromUrl,
toClassArgAppending,
toClassArgReplacing,
toRawString,
toSet,
toSimpleMap,
toStringIfNot,
translateStyleStrBoolArg,
translateStyleStrClassesArg,
translateStyleStrNumberArg,
trimParamStrDelims,
unsetCurrentContainerSizes,
urlContainsPathPart,
urlEndsWithPathPart,
urlStartsWithPath,
utilCache,
varSection,
varsPutAll,
virtualSection,
wrapAsRaw,
wrapRawScript
TEMPLATING API UTILITIES
Intended for use anywhere in production templates and templating macros.
render
macro render
Renders an Ofbiz screen or other resource.
screens.render
utility function.
2016-07-29: The default for the
restoreValues
parameter has been changed to true
.By default, all variables passed using
ctxVars
, globalCtxVars
and reqAttribs
regaintheir previous values when the macro call returns. This helps guard against bugs in templates
that use multiple @render calls as well as nested screens.
2016-11-14: Scope handling is revamped for consistency.
A new
shareScope
parameter is available to control it.The default
shareScope
for ALL types is now false
, meaning the context stack gets pushed/poped.The logical implemented defaults for type
screen
AND section
have CHANGED to false
;they were previously
true
and this is probably a flaw in the original ofbiz handling of screensand sections in ftl files (their XML equivalents perform stack pushing), though it rarely manifests as
an issue due to the ftl bindings being copies from context.
2017-09-10: If both
resource
and name
are empty, this macro simply returns nothing, withoutproducing any error. This is to make it more friendly to template code, so that surrounding #if statements
can be safely omitted.
Parameters
resource
|
((string)) The resource identifier, with format depending on type
|
name
|
((string)) A resource name part, if not already included in the resource If there is no path for the type or path is optional, then name alone should be specified. |
type
|
(screen|menu|form|tree|decorator|section|ftl, default: -dependent on resource-, fallback default: screen) The type of resource to render
NOTE:
screen, menu, form and tree (xxx) can be given a include- prefix. The include- versionguarantees that the include will be processed using the XML include-xxx element.The non- include- versions may be implemented using other meansand may be more efficient, but sometimes it may be needed to force the include mechanism. |
ctxVars
|
((map), default: -empty-) A map of screen context vars to be set before the invocation
WARN:
For type="section" , ctxVars may not work as expected; you may have to passglobalCtxVars instead, due to issues with scoping and nesting.globalCtxVars will work in most cases, but unfortunately they are overriddenby the invoked's sections local vars, so they can't be used to provide overrides.
NOTE:
Currently, this uses #setContextField. To set null, the key values may be set to a special null-representing object found in the global scpNull variable. |
globalCtxVars
|
((map), default: -empty-) A map of screen global context vars to be set before the invocation
NOTE:
Currently, this uses #setGlobalContextField. To set null, the key values may be set to a special null-representing object found in the global scpNull variable. |
reqAttribs
|
((map), default: -empty-) A map of request attributes to be set before the invocation
NOTE:
Currently, this uses #setRequestAttribute. To set null, the key values may be set to a special null-representing object found in the global scpNull variable. |
restoreValues
|
((boolean), default: true) If true, the original values are saved and restored after invocation
NOTE:
2016-07-29: The default for this parameter has been changed to true . |
clearValues
|
((boolean), default: false) If true, the passed request attributes and context vars are removed (or set to null) after invocation |
asString
|
((boolean), default: false) If true, the render will render to a string like a regular FTL macro; otherwise goes straight to Ofbiz's writer In stock Ofbiz, which is also current Scipio default behavior (for compabilitity and speed), render calls go directly to writer, which is faster but cannot be captured using freemarker #assign directive. If you need to captureoutput of @render, pass true here.
NOTE:
not supported for type="section" as this time. |
shareScope
|
((boolean), default: false) Whether context modifications by the widget should be shared with caller (no stack push) or discarded (stack push)
NOTE:
2016-11-14: As of now the logical defaults for all types are false ; prior to this,the specific types screen and section had logical defaults of true,which were probably errors in the original ofbiz. In Scipio, a consistent default of false is now implemented for all types. 2016-11-14: Added for 1.14.3. |
maxDepth
|
((int), default: -1) Max menu levels to render [ menu type only]See widget-menu.xsd include-menu element for details.
|
subMenus
|
(none|active|all, default: all) Sub-menu render filter [ menu type only]See widget-menu.xsd include-menu element for details.
|
secMap
|
((map)) For type="decorator", maps decorator-section names to Freemarker code to execute. WORK-IN-PROGRESS The entries may be TemplateInvoker instances returned from #interpretStd or #interpretStdLoc. Alternatively, simple strings may be passed which will be interpreted as template locations or screen widgets based on extension. Only file locations are supported this way due to security risks of mixing locations and inline content, and because locations allow for optimizations. |
History
Enhanced for 1.14.4 (type="ftl", type="decorator" (WORK-IN-PROGRESS), improved defaults handling).
Enhanced for 1.14.3 (shareScope). Enhanced for 1.14.2.
interpretStd
function interpretStd
Interprets/compiles a string or file location as a template and returns the template
in a self-sufficient template invoker wrapper, which can later be evaluated using
a simple invocation form (by default, simple string evaluation).
?interpret
built-in,with significant differences. Unlike
?interpret
, the default behavioris to treat the invocation as a standalone template render, rather than
evaluating within the current template environment.
In this respect, #interpretStd is closer to the @render directive, but
with no widget renderer involvement.
Furthermore, while ?interpret
returns a directive as wrapper (evaluated using <@value/>
syntax),
by default, #interpretStd returns a scalar (string)-implementing wrapper,
so that it can be evaluated using the same syntax used for regular string variables,
and thus can substitute more easily.
Unlike ?interpret
, variables from the FTL environment are NOT available
from #interpretStd invocations; only variables from the widget renderer
context
(MapStack
) are available. This is closer to @render and is an explicit feature
intended to prevent interfering with FTL environment of parent templates.
Furthermore, by default, the context MapStack
is pushed (see pushCtx
parameter).
This function accepts one parameter which is a map of parameters, described below.
If a single string is supplied instead, it is taken as the inline string template
to interpret, and all other parameters get defaults.
It is also possible to pass the map as the second parameter instead of the first, with
first being the template str.
Parameters
args
|
|
body
|
((string)) An inline string to use as template body The input itself automatically bypasses screen auto-html escaping.
NOTE:
if instead of an args map, the function receives a single string parameter, then it is considered the value of this parameter, and all others receive defaults. |
location
|
((string)) A file location, alternative to inline template The input itself automatically bypasses screen auto-html escaping. |
invokeMode
|
(ofbiz-std, default: ofbiz-std) The general invocation and context mode Possible values:
NOTE:
By default, in all invokeModes, the function will attempt to use template compilation caches appropriate for the current renderer. Currently there is no parameter to disable it and no reason to.
NOTE:
By default, in all invokeModes, the function will attempt to use the same ObjectWrapper as currently in use, meaning the same auto-html-escaping hack will apply. |
invokeCtx
|
((map), default: -mode-dependent-) Context object to use for invocation For ofbiz-std , the default is to use the well-known context variablefound in the freemarker environment at time of invocation.
NOTE:
In most case this should not be set and leave it to fetch the context by itself; in which case, to pass vars, leave pushCtx to true and and pass them in ctxVars instead. |
pushCtx
|
((boolean), default: -mode-dependent-) Whether to push/pop the context around the evaluation For ofbiz-std , the default is true .If the invokeCtx is not a MapStack, this has no effect. |
ctxVars
|
((map)) Additional context vars to pass at time of invocation If pushCtx is true (default), these are lost after render finish. |
unwrapCtxVars
|
((boolean), default: false) Whether to bother to ftl-unwrap the ctxVars or not |
model
|
(hybrid|scalar|directive|hybrid, default: hybrid) The Freemarker TemplateModel to wrap the interpreted/compiled template
|
envOut
|
((boolean), default: false) Whether to output as string or environment writer If set to true, the string-rendering methods of the model ( ?string ) will outputto the current Freemarker environment output INSTEAD of returning as a string, and will instead always return an empty string. This is for advanced usage and is usually only needed so that the string-like models behave more like Ofbiz's screens object, or for performancereasons. This only applies to scalar and hybrid models, and doesn't affectthe directive model or the directive mode of the hybrid model.
|
History
Added for 1.14.3.
Implemented as transform.
interpretStdLoc
function interpretStdLoc
Interprets/compiles a file location as a template and returns the template
in a self-sufficient template invoker wrapper, which can later be evaluated using
a simple invocation form (by default, simple string evaluation).
an args map, it is interpreted to be a file location instead of the template itself.
It is also possible to pass the map as the second parameter instead of the first, with
first being the template location.
Parameters
args
|
See #interpretStd |
History
Added for 1.14.3.
Implemented as transform.
runScript
function runScript
Runs a (groovy) script that prepares data to put into the context
.
Currently, this method only support file locations, and is basic for low overhead. For interpreted/inline scripts, see #interpretStd.
Parameters
location
|
((string)) The resource identifier, usually a component:// file location, usually ends with ".groovy". |
History
Added for 2.1.0.
Implemented as transform.
makeSectionsRenderer
function makeSectionsRenderer
Creates a sections renderer that can be used in place of the "sections" object.
render(name)
method that can be used torender the section by name.
2017-03-28: currently this only implements the sections renderer "ftl" type,
which means the sections cannot be passed back to the widget renderer.
Parameters
type
|
(ftl) (required) The sections renderer type Possible values:
|
sectionsMap
|
((map)) Map of section names to implementations See type for allowed values. |
History
Added for 1.14.3.
Implemented as transform.
pageUrl
macro pageUrl
Builds a page (controller request-map) navigation URL – for direct output into template document (primarily).
accordingly. The old names will continue to function for backward-compatibility, but
using the new names is encouraged. In addition, this macro can now render CMS pages,
which is simply done by passing
id="..."
or name="..."
instead of uri
or a macro body.
See also the function version, #makePageUrl; #makePageUrl should be used instead of @pageUrl
when passing fully-built URLs to other macros (rather than trying to capture the output of @pageUrl)
and in some other cases; meanwhile @pageUrl is more appropriate for writing generate URLs directly
to document output in templates (no intermediate captures). To this end, their default behaviors differ.
(Non-)HTML/JS escaping behavior: By default, neither @pageUrl, #makePageUrl nor any of their variants
perform any HTML or Javascript escaping on their input URIs or parameters – it is not their responsibility.
HTML/JS escaping must be done either (preferably) using #escapeFullUrl, #escapeVal, or (simplest) the optional escapeAs
parameter added
to the URL utilities for Scipio 1.14.2, OR (often problematic) by letting screen html auto-escaping handle it.
Auto-escaping bypass behavior: The macro URL builders behave differently than their function counterparts.
For legacy-compatibility reasons, as an exception to Scipio macros (see standard/htmlTemplate), @pageUrl
does not perform an implied #rawString call on its parameters, and is thus subject to receiving context/data-model
values html-escaped to its inputs due to the renderer's automatic html escaping. By upstream design, @pageUrl
historically received almost exclusively pre-html-escaped values as inputs in ofbiz templates and code.
In contrast, #makePageUrl automatically calls #rawString on its parameters like standard Scipio html macros, such
that the caller only needs to call #rawString if he is composing strings before passing them to the function.
Furthermore, as noted, #makePageUrl performs no extra language escaping by default, so its result remains unescaped
This means the result must be passed to another macro which performs escaping or to #escapeFullUrl – otherwise
it would be unsafe to output. Ultimately the goal is point-of-use escaping.
2016-11-04: The return value behavior for #makePageUrl may be changed in the near future; for the current time,
it better to use #rawString explicitly on the result if you explicitly need a raw unescapted value;
this may be set to return an auto-html-wrapped string instead. If you need to encure escaping, #escapeVal automatically
handles such auto-escaped values in prevision of the future. In most cases such as passing the URL to other
macros, there is no significant impact (and is only made possible) because of other improvements in 1.14.2.
Note that the previous paragraphs describe default behaviors only; the Scipio-modified utilities (all of them) support
extra parameters to handle escaping and switch the uri parameter handling:
escapeAs, rawParams, strict.
Specifically, rawParams
if set to true will make @pageUrl behave like #makePageUrl does by default
– and it is made safe by using escapeAs
to apply html escaping on the final result. Conveniently,
specifying escapeAs
automatically turns on rawParams
, so it's the only one to remember.
In most cases it comes down to using the right tool for the job. #makePageUrl is perfect for passing URLs
to Scipio macros which generally now (since 1.14.2) perform html escaping automatically on their parameters.
So the following suffices for a simple hardcoded URL (for parameter values coming from screen context/data-model, you may
need to use #rawString):
<@menuitem type="link" href=makePageUrl('myRequest?param1=val1¶m2=val2') …/>
Meanwhile, URLs outputted directly into templates or text are usually most quickly done using
@pageUrl, but in newer code it is better done by specifying the escapeAs
parameter,
which will then escape the resulting URL in the given language and turn on the
rawParams
option. Such that, to illustrate, unlike stock ofbiz
there is no need to pre-escape special characters like the parameter delimiter ("&" vs "&"):
<a href="<@pageUrl uri='myRequest?param1=val1¶m2=val2' escapeAs='html'/>">some text</a>
Boolean parameters: In Scipio, boolean arguments can be given as booleans, string representation of booleans
or empty string (ternary, signifying defaults or emulating null).
fullPath
and secure
parameters have different behavior than stock Ofbiz! fullPath behavior change: In Scipio, when fullPath is specified for a controller request, if the
request is defined as secure, a secure URL will be created. This method will now never allow an
insecure URL to built for a controller request marked secure. In stock Ofbiz, this behavior was
different: fullPath could generate insecure URLs to secure requests. In addition, fullPath will
by default no longer downgrade HTTPS connections. To allow downgrades, you must explicitly specify
request it by passing secure false, and this may still produce a secure link if the target
is marked secure. Currently, this applies to all links including inter-webapp links.
secure behavior change: In Scipio, if current browsing is secure, we NEVER downgrade to HTTPS unless
explicitly requested by passing secure false, and secure false may still produce a secure link if
needed. Currently (2016-04-06), for security reasons, this
downgrading request request only applies to the case where the target link is marked as non-secure, such
that in general, setting secure false does not may the link will be insecure in all cases.
In addition, in Scipio, secure flag no longer forces a fullPath link. Specify fullPath true in addition to
secure to force a fullPath link. Links may still generate full-path secure links when needed even
if not requested, however.
Parameters
type
|
(intra-webapp|inter-webapp|cmspage|, default: intra-webapp)
(New in Scipio) |
interWebapp
|
((boolean), default: false) Alias for type="inter-webapp" If true, same as type="inter-webapp"; if false, same as type="" (intra-webapp implied). (New in Scipio) |
uri
|
((string), required) The request URI. May be specified as parameter or as macro nested content For intra-webapp links and with all macro defaults, this should be a controller URI, or if controller false, a relative servlet path (relative to webapp root, excluding webapp context root). For inter-webapp links, if no webSiteId is specified, this must be an absolute path from server root, containing webapp context root and servlet path; if webSiteId specified, this should specified relative like intra-webapp (unless absPath forced to true).
WARN:
At current time (2016-10-14), this macro version of @pageUrl does NOT prevent automatic screen html escaping on the URI parameter, because too many templates use @pageUrl directly without consideration to escaping. However, the function versions of this macro such as #makePageUrl DO bypass the auto screen escaping on this parameter. (New in Scipio) |
absPath
|
((boolean), default: -depends on type-, fallback default: false) If explicit true, the passed uri should be an absolute path from server root (including context root and servlet path) If explicit false (stock Ofbiz default), the passed uri should be relative to control servlet or webapp context. If not specified, will attempt for figure out based on the uri passed and other flags. Current behavior when unspecified:
NOTE:
Behavior when unspecified is NOT currently influenced by present of starting slash ("/"), to try to preserve compability with legacy Ofbiz behavior that accepted one for all link types. It is also ambiguous in the case of intra-webapp non-controller links. (New in Scipio) |
webSiteId
|
((string), default: -current website or none-) Target web site ID This usually should only be specified for inter-webapp links. Will determine the specific target webapp to use.
NOTE:
Some Ofbiz (stock) webapps do not have their own webSiteId, and this is considered normal. (Stock arg, some fixes in Scipio) |
controller
|
((boolean), default: -depends on type-, fallback default: true) If true (stock Ofbiz case), the link is treated as pointing to an Ofbiz controller request URI, and will use information from the controller to generate the link. If false, the link is treated as pointing to any arbitrary servlet or resource. Current behavior when unspecified:
(New in Scipio) |
extLoginKey
|
((boolean), default: false) or string boolean repr If true, this will add the external login key as parameter.
NOTE:
This is currently FALSE by default in all cases including inter-webapp links while details are sorted out. (New in Scipio) |
fullPath
|
((boolean), default: false) or string boolean repr If true, forces a full URL with protocol (HTTP or HTTPS).
WARN:
MODIFIED IN SCIPIO: In Scipio, specifying fullPath true for a controller request marked as secure will always generate a secure URL, not a plain URL. Some control is sacrificed to allow this flag to be used safely and more easily. (Stock arg, enhanced in Scipio: supports both boolean and string containing boolean) |
secure
|
((boolean), default: false) or string boolean repr If true, ensures the resulting URL will be a secure link.
WARN:
MODIFIED IN SCIPIO: This does not guarantee a full URL will be built, only when needed. Pass fullPath true to always force a full path. In addition, this parameter nowrecognizes the value false to force downgrades to HTTP when the target controller requestis marked as non-secure (or if there there is no target request or unknown – since 2016-07-14). (Stock arg, enhanced in Scipio: supports both boolean and string containing boolean) |
encode
|
((boolean), default: true) or string boolean repr If true, pass through HttpServletResponse.encodeURL; otherwise, don't. (Stock arg, enhanced in Scipio: supports both boolean and string containing boolean) |
rawParams
|
((boolean), default: -false, unless escapeAs is set-) Whether macro should call #rawString on its string parameters If true, the macro will automatically call #rawString on uri and other string params, bypassing screen html auto-escaping.If false, strings params are subject to screen html auto-escaping and uri behaves more like nested.For legacy reasons, the default for all URL generation macros (which are derived from stock Ofbiz) defined in this file is false UNLESS the escapeAs parameter is set,in which case this is toggled to true .For URL generation functions (which are new in Scipio), the default is always true .
|
escapeAs
|
(html|js|js-html|...|, default: -empty-) Language in which to escape the whole resulting URL See #escapeFullUrl for possible values. When this is empty (default), the macro performs no escaping whatsoever. If this is set to a language, it toggles rawParams and strict to true , and doing<@pageUrl uri=someUri escapeAs='html'... /> is basically equivalent to doing: <#assign urlContent><@pageUrl uri=someUri rawParams=true strict=true ... /></#assign> ${escapeFullUrl(urlContext, 'html')} Usually, if you use this shortcut, you should use the |
strict
|
((boolean), default: -false, unless escapeAs is set-) Whether to handle only raw strings or recognize pre-escaped strings Default is false unless escapeAs is non-empty, in which case this switches to true .
NOTE:
2016-10-19: Currently this parameter has no effect on this macro (subject to change in a revision).
NOTE:
2016-10-19: Currently this parameter is not passed to #escapeFullUrl (when escapeAs is set), because thepre-escaped ampersand & is too ubiquitous in existing code. |
id
|
((string)) The ID of a CMS page to render, instead of a non-CMS controller request-map.
NOTE:
Not all parameters above apply to CMS page link generation. |
name
|
((string)) The exact name of a CMS page to render, instead of a non-CMS controller request-map.
NOTE:
Not all parameters above apply to CMS page link generation. |
History
Integrated @cmsPageUrl function (id/name) for 2.0.0.
Renamed from @ofbizUrl (2019-01-28) for 2.0.0. Note: Old name will remain working. Enhanced for 1.14.2.
Implemented as transform.
makePageUrl
function makePageUrl
Builds a control/navigation URL – for passing to other utilities (primarily).
but with slight differences in defaults and default behavior.
This is useful to avoid bloating templates with heavy <#assign...><@pageUrl.../></#assign>
captures
and instead passing results directly to other macros and functions.
This function's default escaping behavior is different from the default behavior of its macro counterpart, @pageUrl;
unlike @pageUrl this function was primarily intended to manipulate unescaped strings at input. See @pageUrl for details.
2016-11-04: The return value behavior for #makePageUrl may be changed in the near future; for the current time,
it better to use #rawString explicitly on the result if you explicitly need a raw unescapted value;
this may be set to return an auto-html-wrapped string instead. If you need to encure escaping, #escapeVal automatically
handles such auto-escaped values in prevision of the future. In most cases such as passing the URL to other
macros, there is no significant impact (and is only made possible) because of other improvements in 1.14.2.
Parameters
args
|
Map of @pageUrl arguments OR a string containing a uri (single parameter)
NOTE:
The rawParams default is true , unlike the macro version. |
History
Renamed from #makePageUrl (2019-01-28) for 2.0.0. Note: Old name will remain working.
Enhanced for 1.14.2.
Implemented as transform.
appUrl
macro appUrl
Builds an intra-webapp, non-controller URL from a path (uri) that start from the webapp context root
(thus can point to any servlet within it).
but this is normally used to access another servlet, such as /products/PH-1000.
This calls @pageUrl with absPath=false, interWebapp=false, controller=false by default.
This macro is subject to escaping particularities – see its cousin @pageUrl for details.
Parameters
History
Renamed from @ofbizWebappUrl (2019-01-28) for 2.0.0. Note: Old name will remain working.
Enhanced for 1.14.2.
Implemented as transform.
makeAppUrl
function makeAppUrl
Builds an intra-webapp, non-controller URL from a path (uri) that start from the webapp context root
(thus can point to any servlet within it). Function version of @appUrl.
but this is normally used to access another servlet, such as /products/PH-1000.
This calls @pageUrl with absPath=false, interWebapp=false, controller=false by default.
This function is subject to escaping particularities – see its cousin #makePageUrl for details.
Parameters
args
|
See #makePageUrl, @appUrl |
History
Renamed from #makeAppUrl (2019-01-28) for 2.0.0. Note: Old name will remain working.
Enhanced for 1.14.2.
Implemented as transform.
serverUrl
macro serverUrl
Builds a URL from a path (uri) that starts from server root and includes a webapp context.
Generally, this is used for inter-webapp URLs.
OR requesturi if webSiteId is specified and is a controller request.
This calls @pageUrl with interWebapp=true and optional webSiteId; absPath is left to interpretation
by the implementation or can be overridden; controller is left to interpretation or can be specified.
This macro is subject to escaping particularities – see its cousin @pageUrl for details.
Parameters
History
Renamed from @ofbizInterWebappUrl (2019-01-28) for 2.0.0. Note: Old name will remain working.
Enhanced for 1.14.2.
Implemented as transform.
makeServerUrl
function makeServerUrl
Builds a URL from a path (uri) that starts from server root and includes a webapp context. Function version of @serverUrl.
Generally, this is used for inter-webapp URLs.
OR requesturi if webSiteId is specified and is a controller request.
This calls @pageUrl with interWebapp=true and optional webSiteId; absPath is left to interpretation
by the implementation or can be overridden; controller is left to interpretation or can be specified.
If args is specified as map, "webSiteId" must be passed in args, not as argument.
(This is intentional, to be consistent with macro invocations, emulated for functions)
This function is subject to escaping particularities – see its cousin #makePageUrl for details.
Parameters
args
|
See #makePageUrl, @serverUrl |
webSiteId
|
See #makePageUrl, @serverUrl |
History
Renamed from #makeOfbizInterWebappUrl (2019-01-28) for 2.0.0. Note: Old name will remain working.
Enhanced for 1.14.2.
Implemented as transform.
contentUrl
macro contentUrl
Builds a content/resource URL.
2016-10-18: URL decoding: The default behavior of this macro has been changed from
stock Ofbiz. By default this macro NO LONGER url-decodes the uri/nested. The stock
Ofbiz behavior was presumably originally written to URL-decode whole URLs that had been stored
URL-encoded in the database or encoded elsewhere; however, in the general-purpose use case of this macro (extends
being database-stored URLs), applying URL-decoding by default is dangerous.
In general, if ever applicable, events and services that may receive fully-URL-encoded URLs should URL-decode them
before storing in database – but note that URL-encoded parameters should probably not be decoded if
they are stored with the rest of the URL as-is – only full URLs should be decoded, if received encoded
(in such cases, parameters could effectively be double-encoded, and in that case only the first encoding layer should be removed).
This macro is subject to escaping particularities – see its cousin @pageUrl for details.
2017-07-04: The
variant
parameter's usage in filenames has been fixed in Scipio and will be modified again soon;see the parameter's documentation below.
Parameters
uri
|
(string) URI or path as parameter; alternative to nested
WARN:
At current time (2016-10-14), this macro version of @contentUrl does NOT prevent automatic screen html escaping on the URI parameter, because too many templates use @pageUrl directly without consideration to escaping. However, the function versions of this macro such as #makeContentUrl DO bypass the auto screen escaping on this parameter.
NOTE:
SPECIAL VALUES: Stock ofbiz originally recognized the string "/images/defaultImage.jpg" as a special value; when this value was specified, the variant parameter was ignored.However, this check does not work properly in general. In Scipio, while this behavior is left intact for compatibility with old code, you should simply avoid relying on any such check and not consider "/images/defaultImage.jpg" as a special value, or simply not use it. |
variant
|
((string)) Variant image, normally same image with different dimensions 2017-07-04: The variant name is now appended using one of the following 3 filename patterns:
The NEW cases have been added so that the macro now supports the stock product image upload configuration (see catalog.properties),
SPECIAL PREFIXES:
The variant can be prefixed with one of the following characters:
(Stock Ofbiz parameter, modified in Scipio) |
autoVariant
|
(min|max|true|false|, default: false) Enable automatic variant selection with the specified selection mode
WARN:
Like the variant parameter, in order for this to work properly for an image, the filesystem must containthe proper variants for the image that match the explicit or implied variant configuration ( variantCfg parameter). |
width
|
((int)) Target image width, for autoVariant |
height
|
((int)) Target image height, for autoVariant |
variantCfg
|
Path to a variant configuration file (ImageProperties.xml) If omitted, this will lookup a default configuration file based on the settings in: {{{/framework/common/config/imagecommon.properties}}} The common/default/fallback/reference file is: {{{/framework/common/config/ImageProperties.xml}}} |
ctxPrefix
|
((boolean)|(string), default: false) Contextual path prefix Extra path prefix prepended to the uri, which may replace the central system default prefix if it produces an absolute URL (prefixed with "http:", "https:", or "//"). If string, it is used as given. If boolean: if false, no extra prefix; if true, the context variable (New in Scipio) |
urlDecode
|
((boolean), default: false) Whether to URL-decode (UTF-8) the uri/nested
NOTE:
2016-10-18: The new default is FALSE (changed from stock Ofbiz – or what it would have been). (New in Scipio) |
rawParams
|
((boolean), default: -false, unless escapeAs is set-) Whether macro should call #rawString on its string parameters See @pageUrl for description. |
escapeAs
|
(html|js|js-html|...|, default: -empty-) Language in which to escape the whole resulting URL See #escapeFullUrl for possible values. See @pageUrl for description. |
strict
|
((boolean), default: -false, unless escapeAs is set-) Whether to handle only raw strings or recognize pre-escaped strings This macro must perform checks and concatenations on the passed uri; if pre-escaped values are passed (such as HTML), this parameter must be false. When false, currently (2016-10-19), only HTML and Javascript pre-escaped strings are handled. If escapeAs is set to a specific language, the default for strict becomes true .
NOTE:
2016-10-19: Currently this parameter is not passed to #escapeFullUrl (when escapeAs is set), because thepre-escaped ampersand & is too ubiquitous in existing code.
WARN:
Pre-escaped string handling is heuristic-like and only tries to detect encodings done by UtilCodec class and Freemarker built-ins.In some edge cases, the resulting Javascript may not necessarily be secure! The method will try to warn in log. Known cases:
NOTE:
The function version of this macro, #makeContentUrl, uses true as default for this parameter, unlike this macro. (New in Scipio) |
secure
|
((boolean), default: -true, except for xsl-fo-) Force secure or insecure link flag. Explicit false prevents HTTPS. xsl-fo uses secure false by default for performance and due to connection limitations. Added 2018-08-17. |
type
|
(local|...|, default: -none-) Use alternative "type" content prefix If true, this link will use alternative content prefix from url.properties which are suffixed with this type, in the form: [type].content.url.prefix.secure=https://... [type].content.url.prefix.standard=http://... Notably this is useful for renderers such as xsl-fo that fetch |
...
|
History
Renamed from @ofbizContentUrl (2019-01-28) for 2.0.0. Note: Old name will remain working.
Enhanced for 2.0.0 (secure and type flags) Enhanced for 1.14.4 (variant parameter enhancement; autoVariant parameters added). Enhanced for 1.14.2.
Implemented as transform.
makeContentUrl
function makeContentUrl
Builds a content/resource URL. Function version of the @contentUrl macro.
This function is subject to escaping particularities – see its cousin #makePageUrl for details.
Parameters
args
|
See @contentUrl |
variant
|
See @contentUrl |
rawParams
|
See @contentUrl |
strict
|
See @contentUrl |
History
Renamed from #makeOfbizContentUrl (2019-01-28) for 2.0.0. Note: Old name will remain working.
Enhanced for 1.14.2.
Implemented as transform.
makeContentCtxPrefixUrl
function makeContentCtxPrefixUrl
Version of #makeContentUrl that is preset to recognize the contentPathPrefix
context prefix.
Same as (shorthand for):
makeContentUrl({"uri":someUri, "ctxPrefix":true, …})
This function is subject to escaping particularities – see its cousin #makePageUrl for details.
Parameters
args
|
|
variant
|
History
Renamed from #makeOfbizContentCtxPrefixUrl (2019-01-28) for 2.0.0. Note: Old name will remain working.
Enhanced for 1.14.2.
contentAltUrl
macro contentAltUrl
Builds a content/resource Alt URL, from a URL stored in the database by contentId.
2018-07-31: The ALT URLs come from DataResource.drObjectInfo of ALTERNATIVE_URL content records.
Unlike stock ofbiz, in Scipio, the drObjectInfo field should NOT contain the content url suffix
(default "-content"), which can now be specified in web.xml ContentUrlFilter config (urlSuffix).
2016-10-18: URL decoding: The default behavior of this macro has been changed from
stock Ofbiz. By default this macro NO LONGER url-decodes the URL retrieved by contentId. The stock
Ofbiz behavior was presumably originally written to URL-decode whole URLs that had been stored
URL-encoded in the database.
For consistency and prevention of some less obvious security issues (not as dramatic as @contentUrl),
the default has been changed to not decode by default.
In general, if ever applicable, events and services that may receive fully-URL-encoded URLs should URL-decode them
before storing in database – but note that URL-encoded parameters should probably not be decoded if
they are stored with the rest of the URL as-is – only full URLs should be decoded, if received encoded
(parameters could effectively be double-encoded, and in that case only the first encoding layer should be removed).
This macro is subject to escaping particularities – see its cousin @pageUrl for details.
Parameters
contentId
|
(string) Content ID (Stock Ofbiz parameter) |
viewContent
|
(string) view content (Stock Ofbiz parameter) |
urlDecode
|
((boolean), default: false) Whether to URL-decode (UTF-8) the stored URL
NOTE:
2016-10-18: The new default is FALSE (changed from stock Ofbiz – or what it would have been). (New in Scipio) |
rawParams
|
((boolean), default: -false, unless escapeAs is set-) Whether macro should call #rawString on its string parameters See @pageUrl for description. |
escapeAs
|
(html|js|js-html|...|, default: -empty-) Language in which to escape the whole resulting URL See #escapeFullUrl for possible values. See @pageUrl for description. |
strict
|
((boolean), default: -false, unless escapeAs is set-) Whether to handle only raw strings or recognize pre-escaped strings
NOTE:
2016-10-19: Currently this parameter has no effect on this macro (subject to change in a revision).
NOTE:
2016-10-19: Currently this parameter is not passed to #escapeFullUrl (when escapeAs is set), because thepre-escaped ampersand & is too ubiquitous in existing code. See @pageUrl for description. |
fullPath
|
See @pageUrl |
secure
|
See @pageUrl |
encode
|
See @pageUrl |
params
|
Extra query parameters, as a string. |
...
|
History
Renamed from @ofbizContentAltUrl (2019-01-28) for 2.0.0. Note: Old name will remain working.
Fixed and new params for 2.0.0. Enhanced for 1.14.2.
Implemented as transform.
interpretRequestUri
function interpretRequestUri
Interprets the given request URI/URL resource and transforms into a valid URL if and as needed.
Can help to cut down on macro URL arguments, but may be used anywhere.
The following URI forms are currently interpreted and transformed:
-
pageUrl:// – Any URI that begins with this will be interpreted as a controller URL and ran through @pageUrl/makePageUrl.
Form:
pageUrl://myRequest;fullPath=false;secure=false;encode=true?param1=val1
NOTE:
Order of arguments is strict; args will be stripped.
Parameters
uri
|
uri to interpret for known formats and, if matching, to produce URL |
addExtLoginKey
function addExtLoginKey
Adds the external login key to given url
Parameters
url
|
URL to augment |
escape
|
((boolean), default: true) If true, use escaped param delimiter |
setRequestAttribute
function setRequestAttribute
Sets a request attribute.
This function is enhanced to support more value types and the special value scpNull
to indicate the value null.
Parameters
name
|
|
value
|
Implemented as transform.
setContextField
function setContextField
Sets a field value in context
This function is enhanced to support more value types and the special value scpNull
to indicate the value null.
Parameters
name
|
|
value
|
Implemented as transform.
setGlobalContextField
function setGlobalContextField
Sets a field value in global context.
This function is enhanced to support more value types and the special value scpNull
to indicate the value null.
Parameters
name
|
|
value
|
Implemented as transform.
setVars
function setVars
Sets context variables and request attributes.
to indicate the value null.
Parameters
varMaps
|
((map)) Map of maps of vars to set
|
Implemented as transform.
clearVars
function clearVars
Sets context variables and request attributes.
to indicate the value null.
Parameters
varLists
|
((map)) A map of lists, or map of maps (keys used), of var names to clear
|
Implemented as transform.
extractVars
function extractVars
Gets all the named attributes and context vars.
to indicate the value null.
Parameters
varLists
|
((map)) A map of lists, or map of maps (keys used), of var names to extract values
|
saveNulls
|
((boolean), default: true) If true, null/missing values will get map entries with null value; otherwise, omitted from results
NOTE:
2017-04-28: default is now |
Return Value
A map of maps with same keys as parameters.
History
Modified for 1.14.3.
Implemented as transform.
varSection
macro varSection
Sets context variables and request attributes around a nested block. Can also be used alone.
to indicate the value null.
Parameters
ctxVars
|
((map), default: -empty-) A map of screen context vars to be set before the invocation
NOTE:
Currently, this uses #setContextField. To set null, the key values may be set to a special null-representing object found in the global scpNull variable. |
globalCtxVars
|
((map), default: -empty-) A map of screen global context vars to be set before the invocation
NOTE:
Currently, this uses #setGlobalContextField. To set null, the key values may be set to a special null-representing object found in the global scpNull variable. |
reqAttribs
|
((map), default: -empty-) A map of request attributes to be set before the invocation
NOTE:
Currently, this uses #setRequestAttribute. To set null, the key values may be set to a special null-representing object found in the global scpNull variable. |
restoreValues
|
((boolean), default: true) If true, the original values are saved and restored after invocation
NOTE:
2016-07-29: The default for this parameter has been changed to true . |
clearValues
|
((boolean), default: false) If true, the passed request attributes and context vars are removed (or set to null) after invocation |
Implemented as transform.
virtualSection
macro virtualSection
Defines a virtual section that produces no markup (used in targeted rendering),
with a name of global scope.
This is equivalent to defining a <section>
widget element
(whereas @section is equivalent to <screenlet>
widget element).
See widget-screen.xsd
"contains" expression attribute definition for more information.
this implicitly defines a @renderTarget.
Parameters
name
|
Virtual section name (global scope) |
contains
|
contains-expression See widget-screen.xsd "contains" expression attribute definition for more information.
|
History
Added for 1.14.3.
Implemented as transform.
renderTarget
macro renderTarget
Used within a standard library macro definition to implemented targeted rendering for the directive.
widget-screen.xsd
"contains" expression attribute definition for more information.
Due to possible performance concerns, only a few of the scipio standard Freemarker API currently support this:
@container, @form, @table, @section (NOTE: @section actually matches as "screenlet" element name with % selector).
They are mostly meant to work with the
scpRenderTargetExpr
ID selector (#
). Parameters
dirName
|
Name of the containing directive |
dirArgs
|
((map)) Map of arguments that were passed to the directive The implementation may extract name and ID OR it may do nothing. |
id
|
id |
name
|
name |
History
Added for 1.14.3.
Implemented as transform.
getLabel
function getLabel
Returns label from global label map (uiLabelMap) or resource, or empty string if no label is found,
with automatic screen html-escaping applied (use #rawLabel instead to avoid this).
uiLabelMap
.
By default this function tries to maintain the same behavior as uiLabelMap
with respect to locale
selection and the context map used for label substitutions/arguments.
However, unlike stock uiLabelMap
, this supports explicit message arguments using the msgArgs
parameter.
The default context used by
uiLabelMap
(which is used by default by getLabel
) isnot the current Freemarker namespace nor the same as the
context
variable that ispresent as a freemarker global.
It uses a context created earlier, and the only predictable way to set variables
in it is through the screen global context, using #setGlobalContextField.
Therefore, to pass arguments to label reliably, #getLabel must be used with explicit
msgArgs
parameter. The locale is determined by uiLabelMap. If you must
Parameters
name
|
((string), required) Label name |
resource
|
((string)) Resource name for fallback If label not found in uiLabelMap (preferred), falls back to lookup in thisresource. Usually uiLabelMap is preferred for templates, but sometimes not worth importinga whole file for one label.
NOTE:
If a map is passed as second parameter instead of string, it is interpreted as msgArgs instead of a resource and resource is interpreted as empty. |
msgArgs
|
((map)|(boolean), default: -true / use uiLabelMap's context-) Message arguments If boolean: if true, uses uiLabelMap's default/arbitrary context; if false, prevents any context from being used.
NOTE:
For convenience, msgArgs can be specified as thesecond parameter instead of third (like a java function overload), by passing a map type to the second parameter. So getLabel("xxx", {}) is the same as getLabel("xxx", "", {}) . |
History
Fixed inconsistent return values when missing for 2.0.0.
rawLabel
function rawLabel
Returns label from global label map (uiLabelMap) or resource, or empty string if no label is found,
and prevents automatic html-escaping on the result (unlike #getLabel).
uiLabelMap
.
Shorthand for raw(getLabel(...))
. See #getLabel for more information.
Parameters
name
|
((string), required) Label name |
resource
|
((string)) Resource name for fallback If label not found in uiLabelMap (preferred), falls back to lookup in thisresource. Usually uiLabelMap is preferred for templates, but sometimes not worth importinga whole file for one label.
NOTE:
If a map is passed as second parameter instead of string, it is interpreted as msgArgs instead of a resource and resource is interpreted as empty. |
msgArgs
|
((map)|(boolean), default: -true / use uiLabelMap's context-) Message arguments If boolean: if true, uses uiLabelMap's default/arbitrary context; if false, prevents any context from being used.
NOTE:
For convenience, msgArgs can be specified as thesecond parameter instead of third (like a java function overload), by passing a map type to the second parameter. So rawLabel("xxx", {}) is the same as rawLabel("xxx", "", {}) . |
History
Added for 1.14.2.
rawLabelNoSubst
function rawLabelNoSubst
Same as rawLabel
except no variable substitution is performed (prevented entirely),
so the caller can perform the substitutions instead.
Parameters
name
|
|
resource
|
History
Added for 1.14.4.
getPropertyValue
function getPropertyValue
Gets a property value from a *.properties resource, or void/null if missing or has no content.
Always use default value ("!") or other presence test operator with this function. It behaves differently
than #getPropertyMsg, which always returns a string, for legacy and consistency reasons (UtilProperties method design).
The result from this method is not HTML-encoded, as such values are normally code and not text messages,
in other words not expected to be printed as HTML.
Parameters
resource
|
(required) Resource name |
name
|
(required) Property name |
Implemented as transform.
getEntityPropertyValue
function getEntityPropertyValue
Gets a property value from a *.properties resource or its corresponding SystemProperty entity value,
or void/null if missing or has no content.
Always use default value ("!") or other presence test operator with this function. It behaves differently
than #getPropertyMsg, which always returns a string, for legacy and consistency reasons (UtilProperties method design).
The result from this method is not HTML-encoded, as such values are normally code and not text messages,
in other words not expected to be printed as HTML.
Parameters
resource
|
(required) Resource name |
name
|
(required) Property name |
Implemented as transform.
getPropertyMsg
function getPropertyMsg
Gets a message label from a *Labels.xml property resource, using behavior and rules of the UtilProperties
class (low-level).
For most client templates, you probably want to use #getLabel instead of this function. If you're looking
to read *.properties files, use #getPropertyValue instead. This function is only a bare wrapper around the
UtilProperties#getMessage class method and does not consult the global label map (uiLabelMap) and is not meant
to read *.properties files.
If the name does not exist in the resource, by default this returns the property name, unless true
for optional
is passed in which case it returns empty string (NOT void/missing). The default value operator ("!") is effectively useless if used
with this function (unlike #getPropertyValue).
The default value behavior differs from #getPropertyValue for legacy reasons (UtilProperties method design
and the template code it was menat to replace), and because for label messages (as opposed to #getPropertyValue,
which reads .properties files) it is very rare to need a label fallback in templates.
2019-01: This method description previously erroneously said this method by default returned empty if missing,
which it did not (it always returned the property name, like UtilProperties#getMessage, which it was intended
to replace in templates).
The resulting message is subject to automatic HTML encoding (by Ofbiz).
Use #rawString on the result to prevent escaping.
Parameters
resource
|
(required) Resource name |
name
|
(required) Property name |
msgArgs
|
((map)|(list)|(boolean), default: -false / none-) Substitute values for message template |
locale
|
((locale)|(boolean), default: -true / locale from context-) Locale If boolean: if true, uses locale from context; if false, forced to use system default.
NOTE:
There should almost always be a locale in context or explicit. Fallback on system default usually means something is missing. |
optional
|
(boolean, default: false) If true, missing label returns empty; if false returns key name |
History
Added optional flag and fixed description for 2.0.0.
getPropertyMsgFromLocExpr
function getPropertyMsgFromLocExpr
Gets a message label from a *Labels.xml property resource, using behavior and rules of the UtilProperties
class (low-level), with support
with support for a polyvalent resource expression.
For most client templates, you probably want to use #getLabel instead of this function. If you're looking
to read *.properties files, use #getPropertyValue instead. This function is only a bare wrapper around the
UtilProperties#getMessage class method and does not consult the global label map (uiLabelMap) and is not meant
to read *.properties files.
See #getPropertyMsg for more information; this is nearly the same as #getPropertyMsg but with extra support for a
resource expression.
2019-01: This method description previously erroneously said this method by default returned empty if missing,
which it did not (it always returned the property name, like UtilProperties#getMessage, which it was intended
to replace in templates).
Parameters
resourceExpr
|
(required) Resource name and property name separated with "#", or name alone If name alone, assumes CommonUiLabels for resource. |
msgArgs
|
((map)|(list)|(boolean), default: -false / none-) Substitute values for message template |
locale
|
((locale)|(boolean), default: -true / locale from context-) Explicit locale |
optional
|
(boolean, default: false) If true, missing label returns empty; if false returns key name |
History
Added optional flag and fixed description for 2.0.0.
getTextLabelFromExpr
function getTextLabelFromExpr
Convenience label identifier parsing function that accepts a string in multiple formats
that may designate a label or property as label; if no label, returns empty string.
If textExpr starts with "#PROP:", the following location/name is taken from a properties file (passed through to getPropertyMsgFromLocExpr
If no such prefix in textExpr, returns the text as-is.
Parameters
textExpr
|
(required) Label text expression |
msgArgs
|
((map)|(list), default: -use context-) Substitute values for message template |
locale
|
((locale)|(boolean), default: -true / locale from context-) Explicit locale |
History
Fixed inconsistent return values when missing for 2.0.0.
addParamDelimToUrl
function addParamDelimToUrl
Adds a param delimiter to end of url if needed.
2016-01-21: New special case: if paramDelim is "/" or contains "/", treat differently (because trumps "?")
Parameters
url
|
(required) URL to which to append delimiter |
paramDelim
|
(default: "&") Param delimiter |
paramStarter
|
(default: "?") Query string delimiter, usually "?" Only significant if paramDelim does not contain "/" |
addParamsToStr
function addParamsToStr
Adds parameters from a hash to a URL param string (no full URL logic).
Parameters
paramStr
|
(required) Param string |
paramMap
|
((map), required) Map of keys to values to add |
paramDelim
|
(default: "&") Param delimiter |
includeEmpty
|
((boolean), default: true) If true, include empty values; if false, omit empty values |
urlEncode
|
((boolean), default: false) If true, URL-encode each value. |
addParamsToStrUrlEnc
function addParamsToStrUrlEnc
Adds url-encoded parameters from a hash to a URL param string (no full URL logic).
Parameters
paramStr
|
(required) Param string |
paramMap
|
((map), required) Map of keys to values to add |
paramDelim
|
(default: "&") Param delimiter |
includeEmpty
|
((boolean), default: true) If true, include empty values; if false, omit empty values |
splitStrParams
function splitStrParams
Extracts parameters from a string in the following format and returns as a hash:
name1=val1DELIMname2=val2DELIMname3=val3
where DELIM is specified delimiter (& & , ; etc.).
Parameters
paramStr
|
(required) Param string |
paramDelim
|
(default: "&") Param delimiter |
trimParamStrDelims
function trimParamStrDelims
Strips leading and trailing param delims from a URL param string.
Parameters
paramStr
|
(required) Param string |
paramDelim
|
(default: "&") Param delimiter |
splitStyleNames
function splitStyleNames
Splits a style classes string into sequence, in same order as input.
Parameters
styleString
|
(required) Style string |
Return Value
a sequence of style names, in same order as input.
splitStyleNamesToSet
function splitStyleNamesToSet
Splits a style classes string into a Set of unique elements, not preserving order.
Parameters
styleString
|
(required) Style string containing classes |
Return Value
a java Set of style names (can be seen as sequence)
joinStyleNames
function joinStyleNames
Joins style names in a proper style string of class names.
Usage Examples
<#assign myVar = joinStyleNames("class1", "", " class3")>
Parameters
styleNames...
|
|
styleNames
|
(required) Style names, as arbitrary number of positional parameters |
Return Value
a string of combined style names
joinStyleNamesList
function joinStyleNamesList
Joins style names in a proper style string of class names.
Usage Examples
<#assign myVar = joinStyleNames(["class1", "", " class3"])>
Parameters
styleNames
|
(required) Style names, as sequence |
Return Value
a string of combined style names
getStyleNamesByPrefix
function getStyleNamesByPrefix
Returns all style names with given prefix, as sequence.
now recognizes special syntax scipio class args.
Parameters
styleString
|
(required) Style string |
className
|
|
classNamePrefix
|
(required) Prefix to search for |
Return Value
true if class/style string contains given style, false otherwise
Implemented as transform.
containsStyleName
function containsStyleName
Returns true if class/style string contains given style.
now recognizes special syntax scipio class args.
Parameters
styleString
|
(required) Style string |
className
|
(required) Name of class to find |
Return Value
true if class/style string contains given style, false otherwise
containsStyleNamePrefix
function containsStyleNamePrefix
Returns true if class/style string contains a style with given prefix.
Parameters
styleString
|
(required) Style string |
classNamePrefix
|
(required) Prefix to search for |
Return Value
true if class/style string contains given style prefix, false otherwise
removeStyleNames
function removeStyleNames
Removes style classes from a style string.
strips lead/trailing space.
now recognizes special syntax scipio class args.
Parameters
styleString
|
(required) Style string |
namesToRemove
|
((list)|(string), required) Name or mames to remove Sequence of names OR space-separated string of names OR single name |
Return Value
the style string with names removed, reformatted, in same order as input
stripParamStrFromUrl
function stripParamStrFromUrl
Strips param string (starting with "?" or ";") from url.
Parameters
url
|
(required) URL to strip |
addParamsToUrl
function addParamsToUrl
Adds parameters from a hash to a URL. appends delimiters as needed.
Parameters
url
|
(required) URL to augment |
paramMap
|
((map), required) Map of keys to values to add |
paramDelim
|
(default: "&") Param delimiter |
includeEmpty
|
((boolean), default: true) Include empty values, or if false omit empty values |
escapeUrlParamDelims
function escapeUrlParamDelims
Escapes the URL's parameter delimiters if they are not already escaped.
Parameters
url
|
(required) URL to escape |
paramDelim
|
(default: "&") Param delimiter for substitution |
urlContainsPathPart
function urlContainsPathPart
Checks if the given URL contains the given path part, using proper delimiter checking.
The url and pathPart must not be escaped; use #rawString.
Parameters
url
|
(required) URL to check |
pathPart
|
(required) Path part e.g., /PH-1000
|
camelCaseToDashLowerName
function camelCaseToDashLowerName
Converts camelCase to camel-case.
Parameters
name
|
isObjectType
function isObjectType
Checks the given FTL object against a set of logical types.
The FTL built-in ?is_string and ?is_hash are insufficient for BeanModel-based widget context vars.
In many cases you must use this function.
Parameters
type
|
(string|map|simplemap|complexmap, required)
|
object
|
((object), required) The object to test |
Implemented as transform.
copyObject
function copyObject
Performs a shallow copy of an object (map or list).
The resulting underlying type may differ from the original, but tries to keep the type similar when
possible.
Behavior w.r.t. auto-escaping is currently inconsistent and poorly-defined.
Parameters
object
|
((object)) The object to copy |
Implemented as transform.
copyMap
function copyMap
Performs a shallow copy of a map.
original; in principle tries to preserve, but in most cases will create a simple FTL hash.
Behavior w.r.t. auto-escaping is currently inconsistent and poorly-defined.
- copyObject will also work fine on maps, but this provides more map-specific options.
- This will only copy maps that don't have ?keys support if mode is include ("i") and inExKeys specified.
Parameters
map
|
((map), required) The source map |
mode
|
("e"|"i"|, default: -none-) Optional mode flags
|
inExKeys
|
(optional) List or wrapped set of keys to include or exclude |
Implemented as transform.
rawString
function rawString
Returns the given value, bypassing the screen renderer html auto-escaping, as a simple Freemarker string.
NOTE: 2019-02-14: Now available in shorthand form: #raw
StringUtil.wrapString
, but further simplifiesthe resulting type into a simple Freemarker string.
Can be seen as the reverse operation of #rewrapString.
2016-09-29: Now tolerates non-strings, which will be coerced to strings using ?string operator.
2016-10-20: Now supports multiple parameters, which are each
rawString
-ed and thenconcatenated together.
2019-02-14: This is very similar to the FreeMarker 2.3.27+ built-in,
?no_esc
, but currently,in Scipio, you must use this function instead of the FreeMarker built-in; they are not compatible.
Usage Examples
<@field id="something_${rawString(orderId)}" .../> <@field id="something_${raw(orderId)}" .../>
Parameters
value...
|
((string), required) Value(s) to return without/bypassing screen renderer html auto-escaping If more than one parameter is passed to #rawString, each is applied the logical #rawString bypass, and the result is a concatenation of all the parameters. So raw(var1, " ", var2) is equivalent to raw(var1) + " " + raw(var2) except the former is more efficient. |
History
Enhanced for 1.14.2.
Implemented as transform.
raw
function raw
Returns the given value, bypassing screen renderer html auto-escaping, as a simple Freemarker string.
Shorthand for: #rawString
StringUtil.wrapString
, but further simplifiesthe resulting type into a simple Freemarker string.
Can be seen as the reverse operation of #rewrapString.
2016-09-29: Now tolerates non-strings, which will be coerced to strings using ?string operator.
2016-10-20: Now supports multiple parameters, which are each
rawString
-ed and thenconcatenated together.
2019-02-14: This is very similar to the FreeMarker 2.3.27+ built-in,
?no_esc
, but currently,in Scipio, you must use this function instead of the FreeMarker built-in; they are not compatible.
Usage Examples
<@field id="something_${rawString(orderId)}" .../> <@field id="something_${raw(orderId)}" .../>
Parameters
value...
|
((string), required) Value(s) to return without/bypassing screen renderer html auto-escaping If more than one parameter is passed to #rawString, each is applied the logical #rawString bypass, and the result is a concatenation of all the parameters. So raw(var1, " ", var2) is equivalent to raw(var1) + " " + raw(var2) except the former is more efficient. |
History
Enhanced for 2.0.0.
Implemented as transform.
toRawString
function toRawString
Returns the given value, bypassing screen renderer html auto-escaping, as a simple Freemarker string.
Alias for #rawString.
Parameters
value...
|
Implemented as transform.
toStringIfNot
function toStringIfNot
Returns the given value as a string but only if not already a string.
Result will always be a string (or something implementing
TemplateScalarModel
).
this works using FTL's primitive ?is_string test, which may return TRUE for complex
objects that aren't really strings.
Parameters
value
|
(required) The value to return as string |
History
Added for 1.14.2.
htmlContentString
function htmlContentString
(DEPRECATED)
Returns the given string, free of Ofbiz auto HTML encoding, as a simple Freemarker string, and
depending on current implementation and system policy may process the string for allowed HTML.
DEPRECATED: Use #escapeVal with the allow
option instead.
Parameters
str
|
rewrapObject
function rewrapObject
Re-wraps a value using the Freemarker ObjectWrapper in the current environment (by default)
or a different wrapper, such as one producing simple type adapters, simple types as copies,
and raw strings (without screen html auto-escaping).
come out of the screen's data model. For strings, in a typical rendering, this can be seen as the reverse
operation of #rawString, using simply
rewrapObject(someRawString)
.In this default mode, the value will always be rewrapped, which is the safest mode (but suboptimal).
The function can remove the html auto-escaping behavior of entire maps coming from the data model.
Simply doing rewrapObject(someScreenMap, 'raw')
or rewrapObject(someScreenMap, 'raw-simple')
(to
further simplify the map for iteration).
Using wrapper
and mode
parameters, different object wrappers such as simple-type-producing
ones can be used, and some unnecessary rewrapping can be avoided.
2016-10-20: This method was completely revamped, such that the default behavior is flipped
and behaves more predictably.
2016-10-20: The "simple*" current wrapper derivatives currently only handle maps.
If you are required to use simple or copies for other types of containers, you may
have to use "basic*" in the meantime (TODO), or if raw values are acceptable,
the "raw-simple*" types do handle non-maps.
2016-10-20: Currently only supports "always" (deep) rewrapping mode; ideally need a "needed" and/or "fast"
mode is needed to prevent needless container copies (TODO).
So currently this method is very slow for SimpleHash and similar types, forces copies.
However optimization of this requires many assumptions and risks.
In non-deep cases, for maps, you may also use #toSimpleMap instead, which is more constrained.
Parameters
object
|
((object), required) The source object |
wrapper
|
(current|complex-default|complex-extended|simple|simple-copy|..., default: current) Name/type of wrapper to use General values (abstracted):
Current ObjectWrapper derivatives (abstracted):
NOTE:
2016-10-20: all these "simple" types currently only operate on maps. Lists are usually not as meaningful because the BeansWrapper list type works without any issues. Specific ObjectWrappers (advanced usage – poor abstraction):
|
mode
|
(always-deep|, default: always-deep) Rewrapping mode Values:
NOTE:
For optimization reasons, in the future, the default value may be changed (to something other than "always"), to something better optimized, but the result will not change. If you absolutely count on the "always" strict behavior (for some reason), you should pass it explicitly, but in most cases you should not specify it or you should pass explicit empty. |
History
Rewritten for 1.14.2.
Implemented as transform.
rewrapString
function rewrapString
Re-wraps a string using the Freemarker ObjectWrapper in the current environment (by default)
or a different ObjectWrapper, such as one producing simple adapters or simple types.
Alias for #rewrapObject but expected to receive only strings.
screen renderer html auto-escaping (if enabled) for a specific value.
Parameters
object
|
|
mode
|
History
Added for 1.14.2.
Implemented as transform.
rewrapMap
function rewrapMap
Re-wraps a map using the Freemarker ObjectWrapper in the current environment (by default)
or a different ObjectWrapper, such as one producing simple adapters or simple types.
Alias for #rewrapObject but expected to receive only maps.
Parameters
object
|
|
mode
|
History
Rewritten for 1.14.2.
Implemented as transform.
toSimpleMap
function toSimpleMap
Takes a bean-wrapped map and switches it to a simple map adapter instead, without performing
any copies.
#rewrapObject
except
If the object is not a complex map but already another type of map, returns it as-is. Other types throw errors.
This only changes the complexity of the map; it does NOT prevent auto-escaping. In fact, if
called on certain types of unescaped complex maps, this function may cause auto-escaping to return, which
is why its behavior is to leave maps alone unless they are complex bean maps.
Calling
?keys
on this map may give escaped keys; use #mapKeys to prevent this. Parameters
object
|
((map), required) The source map |
Implemented as transform.
mapKeys
function mapKeys
Gets the logical map keys from any map-like object, whether an FTL hash (?keys) or
a bean-wrapped context var (.ketSet()).
WARN (2016-12-02): Do not rely on this for keying back the values out of the original
map; you should still call #toSimpleMap on the original map before getting the values out of it. This is because BeansWrapper-mapped maps treat some key values such as the "class" key as special.
The resulting keys are unescaped, not passed through auto-escaping, so that
the map values can be keyed back without having to call #rawString.
Parameters
object
|
((map), required) The source map |
Implemented as transform.
concatMaps
function concatMaps
Concatenates two maps similar to FTL "+" hash operator, but works with ofbiz context maps as well.
Using "+" on screen context bean maps causes problems such as "hiding" of the bean map type underneath
an FTL wrapper, which wrecks all subsequent type checks. And others.
It's part of this function's interface that any of the arguments for which ?has_content is false,
will not be used. This covers the cases where non-map types are passed as well ("", [], etc.).
Sometimes an empty non-map type will be passed, should be considered valid.
Shouldn't need to check for non-empty non-map types however, as those are all clear coding errors.
e.g., This is used at beginning of macros that take inlineArgs… or inlineAttribs…
They count on this method to handle empty sequence case.
They also depend on this for the toSimple=true conversion.
Parameters
first
|
((map), required) The first map |
second
|
((map), required) The second map |
toSimple
|
((boolean), default: true) If true, ensure result is a simple hash |
evalToSimpleMap
function evalToSimpleMap
Similar to toSimpleMap but if the object is a string, tries to ?eval it to a map;
otherwise converts the map to a simple hash.
Parameters
object
|
((string)|(map), required) The object to convert to a simple map |
toSet
function toSet
Returns a bean-wrapped java Set for a sequence or collection.
and also org.ofbiz.base.util.UtilMisc.toSet).
If called without parameters, creates new empty set.
Parameters
object
|
((collection)) (optional) The collection If omitted, creates an empty Set. |
Implemented as transform.
compileProgressSuccessAction
function compileProgressSuccessAction
Widget-related progress success action compile (see widget-form.xsd form element extra "attribs" attrib).
Parameters
progressSuccessAction
|
(required) Progress success action |
getCurrentSectionLevel
function getCurrentSectionLevel
Gets current global section level.
Parameters
useDefault
|
((boolean), default: true) If true, if no heading defined, returns default; else return void |
getDefaultSectionLevel
function getDefaultSectionLevel
Gets default section level.
Parameters
setCurrentSectionLevel
function setCurrentSectionLevel
Sets current global section level manually.
Parameters
sLevel
|
((int), required) The section level |
getCurrentHeadingLevel
function getCurrentHeadingLevel
Gets current global heading (title) level.
Parameters
useDefault
|
((boolean), default: true) If true, if no heading defined, return default; else return void |
getDefaultHeadingLevel
function getDefaultHeadingLevel
Gets default heading (title) level.
Parameters
setCurrentHeadingLevel
function setCurrentHeadingLevel
Set current global heading level manually.
Parameters
hLevel
|
((int), required) Heading level |
getRequestNextElemIndex
function getRequestNextElemIndex
Returns and increases a global request count for a certain name.
Parameters
name
|
((string), required) The global request var name |
start
|
((int), default: 1) The initial value |
History
Added for 1.14.2.
objectAsScript
macro objectAsScript
Output a Freemarker variable as a value in Javascript, JSON or similar script language.
To manually prevent the interpretation of a value inside a structure such as a map,
either use the
rawVal
parameter or wrap the nested value itself using#wrapRawScript.
Parameters
object
|
((object), required) The FTL or context object |
lang
|
(js|json, required)
|
wrap
|
((boolean), default: true) If true, wrap in {}, [], or "" as needed; otherwise omit enclosing characters |
hasMore
|
((boolean), default: false) If true, always include trailing separator in hashes and arrays |
escape
|
((boolean), default: true) Escape characters in strings |
maxDepth
|
((int), default: -1) Maximum depth, or -1 for no limit |
rawVal
|
((boolean)|(map)|(list), default: false) If true, treat the object as a pure JSON/other script string. This can be a map or list of boolean to parallel the object, for recursion.
NOTE:
is cumbersome for lists; mostly useful for maps.
NOTE:
this is kept separate from the object for security reasons. |
currDepth
|
wrapAsRaw
function wrapAsRaw
Wraps pre-escaped values for specific languages in a special wrapper object.
When passed to markup- or script-handling macros which normally escape values in these languages,
the values are used as-is with no additional escape.
gets included as
a raw string bypassing html, js or other language escaping.
This include @objectAsScript and macros that escape values using #escapeVal or #escapeFull.
This is only safe to use if an explicit language is passed and the pre-escaping performed
is adequate for that language.
This has no functional relationship to Ofbiz's StringWrapper (
StringUtil.wrapString
or #rawString);its working scope is unrelated to Ofbiz's screen auto-escaping. It is primarily intended
for Scipio macros and templates that use #escapeVal or equivalents.
For more information about escaping in general, see standard/htmlTemplate.ftl.
Parameters
value
|
((string)|(map)) The value to wrap OR a map of languages to strings If this is a string, lang parameter should always be specified.If this is a map, it is a map of languages to strings, for example: {"htmlmarkup":"<em>my title</em>", "raw":"my title"} {"htmlmarkup":"<em>${getLabel('CommonYes')}</em>", "raw":rawLabel('CommonYes')} The supported map languages are the same as the single |
lang
|
(html|js|json|script|...|, default: -empty/unspecific-) The specific language toward which this should be considered "raw" This accepts dash-separated string of names. Values (and special values):
NOTE:
If object is a string (not map), this argument is usually required for safety and correctness.
WARN:
Leaving empty with string object will prevent macro escaping for any language! In virtually all cases you should specify a specific language. The unspecific mode is for rare workarounds only. |
History
Added for 1.14.2.
isWrappedAsRaw
function isWrappedAsRaw
Checks if the object was wrapped with #wrapAsRaw.
This has no functional relationship to Ofbiz's StringWrapper (
StringUtil.wrapString
or #rawString)and will not detect any such wrappers.
Parameters
object
|
the object to check |
lang
|
(html|js|json|script|...|, default: -empty/unspecific-) the specific language toward which this should be considered "raw" |
History
Added for 1.14.2.
getRawWrappedForLang
function getRawWrappedForLang
Gets the raw wrapped value for the given language, as string.
!
).
Parameters
object
|
the object wrapped with #wrapAsRaw |
lang
|
(html|js|json|script|...|, default: -empty/unspecific-) the specific language to get |
History
Added for 1.14.2.
wrapRawScript
function wrapRawScript
Wraps a script value in a special wrapper that marks it as raw script code.
When passed to @objectAsScript will cause the script string to be included as-is, instead of
being interpreted as a value to escape.
#wrapAsRaw(value, "script")
, and easier to remember in relation to @objectAsScript.
Parameters
value
|
|
object
|
the string to wrap |
History
Added for 1.14.2.
isRawScript
function isRawScript
Checks if the value was wrapped using #wrapAsRaw(object, "script")
.
Parameters
object
|
the object to check |
escapeVal
function escapeVal
Escapes an individual value or code "part" for a given language, ignoring and crushing delimiters.
2018-05-10:
css
and cssid
are now available:cssid
aggressively escapes any identifier, while css
is only for escaping string literals between quotes (like "js" and freemarker's ?js). Essentially this is a wrapper around #rawString and language encoders. It abstracts the encoder selection.
It first performs a #rawString call to bypass the screen auto-escaping on the value.
In addition, this function accepts values produced by #wrapAsRaw. These can be used to bypass the escaping in part or in full.
If the value was wrapped using the same language as specified in this call, the wrapped value will be used as-is.
-
2016-10-05: Currently, this is mostly implemented using Freemarker built-ins such as
?html
,?js
, etc. but is subject to change.
Although Freemarker built-ins can still be used directly in templates and client macros, use of this function
is recommended to centralize the escaping logic, automatically prevent some forms of double-escaping, create better versatility,
and help hasten resolution of security issues.
IMPL NOTE:
All Scipio standard API implementations, however, should strictly use this function.
For more information about escaping in general, see standard/htmlTemplate.ftl.
Single languages
HTML: Two language identifiers are supported: "html" and "htmlmarkup".
Callers of #escapeVal should usually use "html" on html attributes, and "htmlmarkup" on text placed within element body.
By default, this function escapes all markup delimiters for both.
The difference is that callers upstream using #wrapAsRaw will then able to override markup specifically using:
#wrapAsRaw(xxx, 'htmlmarkup')
or for all html (only if careful to escape for attributes safely) using:
#wrapAsRaw(xxx, 'html')
"html" is also a special case because it also fills in for "htmlmarkup" (if not included in the #wrapAsRaw call),
but not vice-versa since markup cannot be used in attributes.
Callers upstream using #wrapAsRaw should usually use "htmlmarkup" in most cases.
Javascript, JSON: Only simple single string parts are supported via "js" and "json" (and some variants).
This can ONLY encode strings between ""
or ''
.
It is impossible to safely encode javascript outside string literals (see OWASP).
Composed languages
Javascript and HTML: For Javascript strings placed within HTML attributes (e.g. events such as onchange
),
typically "js-html" is needed.
From template perspective, macros generally escape html by default, so templates only need to escape the javascript part.
Validation and allowed code
This function is scheduled to support some language-specific code validation/filters, to provide
a middle ground between allowing no code (full escaping – default behavior) and allowing all code (no escaping – #rawString alone).
See the opts.allow
parameter below.
It is usually logical to perform such validation nearest to point-of-use as possible using this function.
However, note that, in addition, it is usually either a very good idea or simply required to validate input
such as code markup before storage in database (server-side, or even client-side yet in addition), long before
and elsewhere from a template containing this function call is rendered.
Thus, the safest solution is to do both; validate markup in content from actors server-side, and apply
the equivalent filter using this function in templates. This guards against errors and stale content spanning security policy
and filter implementation changes.
Validation and allowed code filters are not fully implemented (TODO), but will be supported by this function.
Parameters
value
|
The string or string-like value to escape 2016-09-29: This now automatically coerces non-strings to string, for convenience. |
lang
|
(js|jsdq|json|html|htmlmarkup|url|xml|css|cssid|js-html|html-js|htmlmarkup-js|raw) The target language for escaping These are analogous to the Freemarker built-in counterparts of same names, but with implementation details subject to change. In composed types, the order is meaningful, such that "js-html" performs like ?js?html and "html-js" like ?html?js .Values and special values:
|
opts
|
((map)) Additional options, including language-specific options Members:
|
History
Modified for 1.14.4 (added css
, cssid
, removed the old style
synonym, opts.allow implementation)
Added for 1.14.2, previously known as {{{escapePart}}}.
escapePart
function escapePart
(DEPRECATED)
Escapes an individual value or code "part" for a given language, ignoring and crushing delimiters.
DEPRECATED: Replaced by #escapeVal.
Parameters
value
|
|
lang
|
|
opts
|
escapeFull
function escapeFull
(DEPRECATED)
Encodes/escapes a value in a given language.
DEPRECATED: This was never properly defined or implemented and no longer meaningful. Use #escapeVal or #escapeFullUrl.
Related
#escapeVal #escapeFullUrl
Parameters
value
|
|
lang
|
|
opts
|
escapeFullUrl
function escapeFullUrl
Escapes a complete URL for safe insertion in code of a given language.
2018-05-10:
css
is now available; see #escapeVal for details. It must only be used for values between quotes. Essentially this is a wrapper around #rawString and language encoders. It abstracts the encoder selection.
It first performs a #rawString call to bypass the screen auto-escaping on the value.
For compability reasons, this function when not in strict mode (default is not strict) accepts param delimiters
in either the escaped &
form or unescaped &
form.
Ideally, such escaped delimiters would not be received, but they are very prevalent in Ofbiz due
to early escaping.
In addition, this function accepts values produced by #wrapAsRaw. These can be used to bypass the escaping in part or in full.
If the value was wrapped using the same language as specified in this call, the wrapped value will be used as-is.
Note that most times, this is not nearly as useful as it is for #escapeVal.
-
2016-10-05: Currently, this is mostly implemented using Freemarker built-ins such as
?html
,?js
, etc. but is subject to change.
Although Freemarker built-ins can still be used directly in templates and client macros, use of this function
is recommended to centralize the escaping logic, automatically prevent some forms of double-escaping, create better versatility,
and help hasten resolution of security issues.
IMPL NOTE:
All Scipio standard API implementations, however, should strictly use this function.
For more information about escaping in general, see standard/htmlTemplate.ftl.
Usage Examples
<a href="${escapeFullUrl('http://www.ilscipio.com/test?param1=val1¶m2=val2;jsessionid=fake', 'html')}">Link</a> <@script> var link = "${escapeFullUrl('http://www.ilscipio.com/test?param1=val1¶m2=val2;jsessionid=fake', 'js')}"; </@script>
Parameters
value
|
The string or string-like value to escape |
lang
|
(html|js|jsdq|json|js-html|jsdq-html|xml|css|raw) The target language
WARN:
Inserting URLs into CSS (using url() ) is known to be unsafe even with escaping. |
opts
|
((map)) Additional options, including lang-specific options Members:
|
escapeMsg
function escapeMsg
Escapes a general message or description field, with interpretation support for certain languages.
for lang=="htmlmarkup".
This function is largely a point-of-use compatibility version of stock ofbiz behavior
often used on description fields, event messages, etc.
For event messages, please use #escapeEventMsg instead for specific support.
Parameters
value
|
The string or string-like value to escape See #escapeVal for details. |
lang
|
(js|jsdq|json|html|htmlmarkup|url|xml|css|js-html|html-js|htmlmarkup-js|raw) The target language for escaping See #escapeVal for details. |
opts
|
((map)) Additional options, including language-specific options
See #escapeVal for details. |
History
Added for 1.14.4 (2018-02-27).
escapeEventMsg
function escapeEventMsg
Escapes a legacy screen event success or error message string for safe insertion in event/error message templates.
consistent escaping and interpreting behavior for the templates that output event error and success messages,
notably messages.ftl (framework/common/webcommon/includes/messages.ftl) and error.ftl.
Currently, this attempts to support the legacy ofbiz behavior of line-break translation
for errorMessage, errorMessageList, eventMessage and eventMessageList when lang=="htmlmarkup".
Traditionally this was done obscurely in ofbiz by the ScreenRenderer.java class, but that was
a design error (not point-of-use escaping) and caused several issues, so this is being
improved for Scipio.
Parameters
value
|
The string or string-like value to escape See #escapeVal for details. |
lang
|
(js|jsdq|json|html|htmlmarkup|url|xml|css|js-html|html-js|htmlmarkup-js|raw) The target language for escaping See #escapeVal for details. |
opts
|
((map)) Additional options, including language-specific options
See #escapeVal for details. |
History
Added for 1.14.4 (2018-02-27).
sanitizeMarkup
function sanitizeMarkup
Sanitizes a value containing markup in a language such as HTML, using
deep validation where possible.
ones may be added by adding new Java factories.
Contrary to #escapeVal, here the language names should not be suffixed with "*markup".
For "html", use "html-[policy]", NOT "htmlmarkup-*".
"url" lang has no effect in Scipio using this method! It returns the original string.
URL escaping should be done on individual url parameters, using #escapeVal, not sanitize.
Historically, the "url" lang was misused in stock ofbiz content wrappers, leading to its sanitize
method being disabled in Scipio.
This method is expensive to use at run-time, and should not be used
in performance-critical areas; for that, the *ContentWrapper classes
offer a cache around sanitized content.
Parameters
value
|
The string or string-like value to escape 2016-09-29: This now automatically coerces non-strings to string, for convenience. |
langPolicy
|
The full language and sanitizer policy to use, usually in the form: lang-policye.g., html-strict, html-default, etc. (do NOT use "htmlmarkup" here; for #escapeVal only) The possible values are defined in utilcodec.properties and printed in system log at startup. |
History
Added for 1.14.4.
Implemented as transform.
API-WRITING UTILITIES
Intended to assist implementation of template macros.
contentArgRender
macro contentArgRender
Renders an argument supposed to contain a string or macro representing template content.
If it is a macro, it must accept a single args
parameter (map), which may
be empty or populating depending on the specific point of use.
Parameters
content
|
((string)|(macro)) The content to render |
doTrim
|
((boolean), default: false) If string, trim it |
args
|
((map)) Map of arguments to pass to macro |
mergeArgMaps
function mergeArgMaps
Merges scipio macro inlineArgs/args/defaultArgs/overrideArgs argument maps for macros implementing
the advanced argument interface.
<#macro name args={} inlineArgs...>
pattern, whereby inlineArgs map is merged over the args map, over defaults.
It cannot be used for the 'attribs={} inlineAttribs...' pattern (see mergeAttribMaps).
Instead, it can help in implementing that pattern within the 'args={} inlineArgs...' pattern.
This is specific to scipio macro patterns and may contain extra handling besides concatenating maps.
For one, this currently records the macro's static named args as passed in the defaultArgs and overrideArgs maps
in a list of names with the key "localArgNames" in the resulting map.
It will also append the names to a list read back from the incoming "args" map with
key name "allArgNames", append to it, and return it again as "allArgNames".
allArgNames allows arg names to be automatically accumulated
between delegating/overriding macro calls that make use of mergeArgMaps without
having to recreate new intermediate maps. allArgNames keep track of all the explicit
args used by all the macros in a call chain, which can then be used to identify
the remaining "extra" arguments (analogous to varArgs in FTL's <#macro varArgs...>).
in some cases allArgNames accumulation and reuse of maps could be undesirable.
(currently workaround this by using localArgNames only and/or creating new intermediate maps).
currently the result may often contain duplicate names (is not a set).
This is normal and should not be changed; code that uses these lists may make a Set if needed.
The result is the caller can access any arg names in the resulting map which had a default
value using simple syntax guaranteed not to cause missing values. e.g
<#macro name args={} inlineArgs...> <#local args = mergeArgMaps(inlineArgs, args, {"myParam1":true})> <#if args.myParam1> ... </#if> </#macro>
OR
<#macro name args={} inlineArgs...> <#local args = mergeArgMaps(inlineArgs, args, {"myParam1":true})> <#local dummy = localsPutAll(args)> <#if myParam1> ... </#if> </#macro>
This can also be used for functions, but for functions, the inlineArgs param should always
be passed an empty hash (functions don't support named parameters).
Parameters
args
|
((map)) The args map (normal priority) May be any type of map. |
inlineArgs
|
((inline-args)) The macro's inline args (high priority) Expects either FTL hash or empty sequence (but not non-empty sequence). |
defaultArgs
|
((map)) Arg defaults (lowest priority) Expects an FTL hash only. The key names in this map are also used to create a list of the known arguments this macro accepts. As such, even if the macro does not need this map, it should pass it along with the names of all supported arguments. The names end up in the resulting map as localArgNames. |
overrideArgs
|
((map)) Extra macro args that override all others (highest priority) Expects an FTL hash ONLY (not context map). The names used here also count toward the localArgNames.
NOTE:
If a key is present in both defaultArgs and overrideArgs, it will result in two names added to localArgNames/allArgNames. The code that finally uses those lists should make a Set if it needs to.
NOTE:
This map is present for cases where the others are insufficient. but otherwise should avoid using this map when possible. |
mergeArgMapsEx
function mergeArgMapsEx
Variant of #mergeArgMaps that returns more than one map.
Parameters
args
|
See #mergeArgMaps |
inlineArgs
|
See #mergeArgMaps |
defaultArgs
|
See #mergeArgMaps |
overrideArgs
|
See #mergeArgMaps |
Return Value
a map of arg maps: allArgs
(full combined), explArgs
(only explicitly passed args)
mergeArgMapsBasic
function mergeArgMapsBasic
A version of mergeArgMaps that only merges maps, but doesn't perform any special implied
operations on them.
Parameters
args
|
See #mergeArgMaps |
inlineArgs
|
See #mergeArgMaps |
defaultArgs
|
See #mergeArgMaps |
overrideArgs
|
See #mergeArgMaps |
getScipioMacroDefaultArgs
function getScipioMacroDefaultArgs
Returns all the known args and default args for a scipio macro that uses the advanced
args pattern, where the macro resides in the given namespace (or namespace-like map).
should automatically give one such as empty string).
If namespace is omitted, currently (2015-12-14), this will use ".vars" as the namespace.
Parameters
name
|
|
namespace
|
mergeAttribMaps
function mergeAttribMaps
Merges scipio macro attribs/inlineAttribs/defaultAttribs/overrideAttribs maps for macros implementing
a special attribs/inlineAttribs pattern for HTML element attributes.
<#macro name arg1="" arg2="" ... argN="" attribs={} inlineAttribs...>
pattern, whereby inlineAttribs map is merged over the attribs map, and these maps only contain extra
element attributes.
This pattern is simpler but much less flexible than the 'args={} inlineArgs...' pattern.
They are different and NOT interchangeable.
Parameters are analogous to #mergeArgMaps but implied logic differs.
Parameters
attribs
|
|
inlineAttribs
|
|
defaultAttribs
|
|
overrideAttribs
|
makeAttribMapFromArgs
function makeAttribMapFromArgMap
Takes an args map returned by mergeArgMaps (NOT mergeArgMapsBasic) and checks it for an "attribs"
sub-map and blends them together logically to make an attribs map.
2016-08-02: This function has been modified so that the result fully represents a usable
attribs map as-is. It no longer contains superfluous members (allArgNames, localArgNames, etc.).
Parameters
args
|
|
excludes
|
Implemented as transform.
getAttribMapAllExcludes
function getAttribMapAllExcludes
Returns the attrib map excludes from the given attribs map, which is composed of its
"scipioExcludeNames" and "scipioNoExcludeNames" members, plus optional additional
includes passed as arguments.
The result is returned as a bean-wrapped Set.
Parameters
attribs
|
|
exclude
|
|
noExclude
|
getFilteredAttribMap
function getFilteredAttribMap
Returns the attrib map with all the basic excludes applied.
Parameters
attribs
|
|
exclude
|
|
noExclude
|
History
Added for 1.14.2.
compileClassArg
function compileClassArg
Compiles a class argument as common to most standard macros,
producing a simple list of class names from a class arg, adding optional default.
Generally not for use in templates (though may still be useful in some).
Macro Class Arguments
Macro class arguments can have essential (required) and non-essential (default)
defaults and values added by the macro before producing the final class attribute.
The essentials can't be omitted.
The non-essentials in some cases you want to replace with value and other times
you want to keep them but only add extra classes. Having multiple args for each elem
class arg gets heavy.
So to address all the cases, these functions cause the class arg on all supporting macros
to accept following values:
-
string with
+
prefix or empty string""
: Means allow macro to add non-essential default classes.
The class names after the+
will be appended to any classes added
by the macro, and will never replace macro defaults.
This means the same as boolean true but with extra classes provided.
In other words, appends extra classes. -
string with
=
prefix or non-empty string: Means prevent macro from adding non-essential default classes.
Class names given will replace macro defaults, i.e. non-essential classes.
Macro may still add its own required classes.
This is the same as boolean false but with replacement classes provided.
In other words, replaces default (non-essential) classes.
In a few cases, the non-essential defaults are "conditionally essential"
so class="="
makes little sense, but usually doesn't warrant special handling.
- Not all macros act on all prefixes, though the syntax is always accepted.
-
Currently, in some cases of traditional Ofbiz templating, the logic above breaks too much compatibility. So it is not universally used
for screen/form/menu widgets although often supported.
For these, in some places anxxxExplicit
version of functions are used instead which will only
replace if explicitly prefixed with=
, but not if no prefix. Otherwise, existing widget styles break
the grid everywhere.
Usage Examples
In macro implementations, compileClassArg should usually be used as late as possible: <#local classes = compileClassArg(class)> or <#local classes = compileClassArg(class, "default-class")> Specifying the default value is the same as doing: <#local class = addClassArgDefault(class, "default-class")> <#local classes = compileClassArg(class)>
Parameters
class
|
|
defaultVal
|
compileClassArgExplicit
function compileClassArgExplicit
Version of compileClassArg that will only use defaultVal if it explicitly starts with "="; needed
for compatibility in some cases
Parameters
class
|
|
defaultVal
|
compiledClassAttribStr
macro compiledClassAttribStr
Produces a class string attribute at same time as compiling class arg, with optional default,
with leading space.
Parameters
class
|
|
defaultVal
|
compiledClassAttribStrExplicit
macro compiledClassAttribStrExplicit
Explicit version of #compiledClassAttribStr.
Parameters
class
|
|
defaultVal
|
toClassArgAppending
function toClassArgAppending
Converts simple class name to an appending class
Parameters
newClass
|
toClassArgReplacing
function toClassArgReplacing
Converts simple class name to a replacing class
Parameters
newClass
|
addClassArg
function addClassArg
Adds a required class, that must appear in class string.
Does not influence the default value logic perceived by addClassArgDefault (user intention preserved).
It does this by prefixing result with "+" string where necessary.
ADD CLASS ARG FUNCTIONS
These functions take a template-level/logical scipio macro "class" arg and add to it the given class.
Should be called by the implementing macros only.
Depending on the previous value in class, non-essential (default) values may simply be discarded, but
essentials (required) will always be added in some way, transforming the class value.
The newClass parameter is a simple string literal and is not interpreted.
These are non-destructive except for addClassArgReplacing which always causes the string to become
a replacing string ("=").
Parameters
class
|
|
newClass
|
addClassArgReplacing
function addClassArgReplacing
Special case of addClassArg where the required class will become a replacing string ("=" prefix, as in "=my-class"),
though will not squash previous values.
This destroys information about what macro user requested and affects the default value logic
perceived by addClassArgDefault.
Parameters
class
|
|
newClass
|
addClassArgDefault
function addClassArgDefault
Adds a class only if the class arg does not contain default-replacing classes.
It adds default if class is true, empty or starts with "+".
Parameters
class
|
|
newClass
|
addClassArgDefaultExplicit
function addClassArgDefaultExplicit
Version of addClassArgDefault that will only replace default if it explicitly starts with "="; needed
for compatibility in some cases
Parameters
class
|
|
newClass
|
combineClassArgs
function combineClassArgs
Logically combines two template-level scipio macro "class" arguments.
The second almost always overrides the first, except when second is appending a class
with "+", in which case depends on the first.
of previous values (in addition of being an appending value itself).
Even if the second arg is merely "+" (which usually means "use defaults" for scipio macros),
this method will return "+" and dismiss the first argument. "+" is not treated as
pass-through here. This does not seem consistent,
but is chosen explicitly so that caller/macro decides what the "pass-through" value
is supposed to be. Here, we assume "+" was passed explicitly to override the first.
We only treat "+" with an arg.
In other words, can see this as another kludge for lack of null values in freemarker.
Parameters
first
|
|
second
|
getPlainClassArgNames
function getPlainClassArgNames
Returns class names without their Scipio-supported prefix.
Parameters
class
|
getClassArgPrefix
function getClassArgPrefix
Returns the Scipio-supported class prefix from a class arg.
Parameters
class
|
translateStyleStrClassesArg
function translateStyleStrClassesArg
Translates a class arg from a string-only representation to a FTL value which can be passed as
macro args processed by compileClassArg.
Needed for string repr of booleans and because empty string "" may have different meanings
depending on context. also translates booleans.
Parameters
val
|
translateStyleStrBoolArg
function translateStyleStrBoolArg
Translates a bool arg from a string-only representation to a FTL value which can be passed as
macro args expected to be booleans.
Parameters
val
|
translateStyleStrNumberArg
function translateStyleStrNumberArg
Translates a number arg from a string-only representation to a FTL value which can be passed as
macro args expected to be numbers.
Parameters
val
|
addStringToBoolStringVal
function addStringToBoolStringVal
Adds a string with optional delimiter to a string that supports boolean values.
Parameters
orig
|
|
toAdd
|
|
delim
|
maskValueLeft
function maskValueLeft
Replaces the first part of the string with a masking character (default "*").
The result is automatically HTML-escaped, so you may need to use #rawString in some cases.
Usage Examples
${maskValueLeft("123456781234", -4)} // ${maskValueLeft("123456781234", 8, "X")}
Parameters
value
|
((object), required) Value, usually a string; if not string, coerced to string first |
maskLength
|
((int), required) If greater than zero, the number of characters to mask from the left; if negative, the number of characters to leave unmasked from the right; if zero, returns the original string. If maskLength is greater than zero and the string is less than maskLength, returns a string of maskLength masked characters; if maskLength is negative and the string is less than the absolute value of maskLength, returns the original string. Thus, negative values depend on the value's size as a string. |
maskChar
|
((string), default: "*") The mask character (should be length 1) |
History
Added for 2.0.0.
Implemented as transform.
maskValueRight
function maskValueRight
Replaces the last part of the string with a masking character (default "*").
The result is automatically HTML-escaped, so you may need to use #rawString in some cases.
Usage Examples
${maskValueRight("123456781234", 4)} ${maskValueRight("123456781234", -8, "X")}
Parameters
value
|
((object), required) Value, usually a string; if not string, coerced to string first |
maskLength
|
((int), required) If greater than zero, the number of characters to mask from the right; if negative, the number of characters to leave unmasked from the left; if zero, returns the original string. If maskLength is greater than zero and the string is less than maskLength, returns a string of maskLength masked characters; if maskLength is negative and the string is less than the absolute value of maskLength, returns the original string. Thus, negative values depend on the value's size as a string. |
maskChar
|
((string), default: "*") The mask character (should be length 1) |
History
Added for 2.0.0.
Implemented as transform.
pushRequestStack
function pushRequestStack
Pushes a value onto a global stack variable in request scope (request attributes, or if no request, globals).
Parameters
name
|
(required) Global request stack var name Must be unique across all known types of contexts (request attribs, screen context, FTL globals) |
val
|
((object)) Value |
Implemented as transform.
popRequestStack
function popRequestStack
Pops a global stack variable in request scope (request attributes, or if no request, globals).
AUTO-ESCAPING: Unlike
request.getAttribute
, values retrieved are not auto-escaped,unless they were inserted already escaped. In general, what you put in is what you get out.
Parameters
name
|
(required) Global request stack var name Must be unique across all known types of contexts (request attribs, screen context, FTL globals) |
Implemented as transform.
setLastRequestStack
function setLastRequestStack
Same as doing popRequestStack + pushRequestStack, but will never fail if stack is empty - will simply
do a pushRequestStack, and much more efficient.
Parameters
name
|
(required) Global request stack var name Must be unique across all known types of contexts (request attribs, screen context, FTL globals) |
val
|
(required) Value |
Implemented as transform.
readRequestStack
function readRequestStack
Reads the last value added to the named global stack variable in request scope
(request attributes, or if no request, globals), without popping.
AUTO-ESCAPING: Unlike
request.getAttribute
, values retrieved are not auto-escaped,unless they were inserted already escaped. In general, what you put in is what you get out.
Parameters
name
|
(required) Global request stack var name Must be unique across all known types of contexts (request attribs, screen context, FTL globals) |
Implemented as transform.
getRequestStackAsList
function getRequestStackAsList
Gets a copy of the named request stack as a list (read-only).
AUTO-ESCAPING: Unlike
request.getAttribute
, values retrieved are not auto-escaped,unless they were inserted already escaped. In general, what you put in is what you get out.
Parameters
name
|
(required) Global request stack var name Must be unique across all known types of contexts (request attribs, screen context, FTL globals) |
listType
|
(copy|orig, default: copy)
|
Implemented as transform.
getRequestStackSize
function getRequestStackSize
Gets the current size of the named stack.
If the stack doesn't exist, returns void, so can be used to check if a stack exists using ??
operator.
Parameters
name
|
(required) Global request stack var name Must be unique across all known types of contexts (request attribs, screen context, FTL globals) |
History
Added for 1.14.2.
Implemented as transform.
setRequestVar
function setRequestVar
Sets a global var in request scope (request attributes, or if no request, globals).
Parameters
name
|
(required) Global request var name Must be unique across all known types of contexts (request attribs, screen context, FTL globals) |
val
|
((object), required) Value |
mode
|
(u|w|, default: -empty-) Modes
NOTE:
"u" and "w" modes are usually unnecessary and should be avoided in most template and macro code. |
Implemented as transform.
getRequestVar
function getRequestVar
Gets a global var from request scope (request attributes, or if no request, globals).
Not meant to be used on regular request attributes.
AUTO-ESCAPING: Unlike
request.getAttribute
, values retrieved are not auto-escaped,unless they were inserted already escaped. In general, what you put in is what you get out.
Parameters
name
|
(required) Global request var name Must be unique across all known types of contexts (request attribs, screen context, FTL globals) |
Implemented as transform.
varsPutAll
function varsPutAll
Puts all key-value pairs from given map into FTL current namespace variables (#assign).
Parameters
map
|
the source map |
mode
|
(e|i|, default: -empty-) Optional mode flags
|
inExKeys
|
((list)|(set), default: -empty-) Optional list or wrapped set of keys to include or exclude |
Implemented as transform.
globalsPutAll
function globalsPutAll
Puts all key-value pairs from given map into FTL globals (#global).
Parameters
map
|
See #varsPutAll |
mode
|
See #varsPutAll |
inExKeys
|
See #varsPutAll |
Implemented as transform.
localsPutAll
function localsPutAll
Puts all key-value pairs from given map into FTL globals (#local).
Parameters
map
|
See #varsPutAll |
mode
|
See #varsPutAll |
inExKeys
|
See #varsPutAll |
Implemented as transform.
elemAttribStr
macro elemAttribStr
Prints a string of element attributes. (HTML, FO, XML)
This is a very generic function; for common implementation, see @commonElemAttribStr.
If a context map is passed containing strings, they will not be auto-HTML-escaped by the renderer.
2016-09-30: This now automatically HTML-escapes attribute values by default; see
escapeLang
parameter. Parameters
attribs
|
((map)) Map of attribute-value pairs It currently accepts string format as a fallback/legacy support, but this is highly discouraged and other args won't work with it. |
alt
|
((boolean)) If true alternate row (odd), if false regular (even) |
selected
|
((boolean)) If true row is marked selected |
exclude
|
((list)) List of attrib names to skip |
attribNamePrefix
|
((string)) Add this prefix to attribute names |
alwaysAddPrefix
|
((boolean)) If false, only add prefix if not already has prefix (default true) |
attribNamePrefixStrip
|
((string)) Remove this prefix from all attrib names |
attribNameSubstitutes
|
((map)) Map of attrib names to substitute attrib names
NOTES:
|
camelCaseToDashLowerNames
|
((boolean)) If true converts attrib names from camelCase to camel-case at the very end |
emptyValToken
|
((string)) When this value encountered, will include an empty attrib |
noValToken
|
((string)) When this value encountered, will include an attrib with no value |
escapeLang
|
(html|...|none, default: 'html') Language to escape each attribute (passed to #escapeVal) Callers may bypass escaping by wrapping their values using #wrapAsRaw. |
includeEmpty
|
attribSpecialVal
function attribSpecialVal
Returns a special value that can be passed to some attribs maps arguments on
macros (works via @elemAttribStr).
Parameters
type
|
(none|empty) The special value type |
History
Added for 1.14.2.
isAttribSpecialVal
function isAttribSpecialVal
Checks if a value is one returned by #attribSpecialVal.
Parameters
val
|
|
type
|
(none|empty|, default: -empty-) The special value type to test for, or empty for any special value |
object
|
the object to test |
History
Added for 1.14.2.
formattedDate
macro formattedDate
Renders a formatted date.
formattedDate by default renders the "date" type but it also doubles as handler for the other types
(which also have convenience wrappers below).
The locale and timeZone (explicit or from context) should not resolve to null/empty;
if they do a log warning is printed.
Parameters
date
|
((date), required) The date |
dateType
|
(date-time|timestamp|date|time, default: date) "timestamp" and "date-time" are synonymous. |
defaultVal
|
If no output is produced (empty), this value (string) will be shown instead |
locale
|
((locale), default: -locale from context-) Override locale |
timeZone
|
((timezone), default: -timeZone from context-) Override time zones |
dateTimeFormat
|
formattedDateTime
macro formattedDateTime
Renders a formatted date-time value (convenience wrapper).
The locale and timeZone (explicit or from context) should not resolve to null/empty;
if they do a log warning is printed.
Parameters
date
|
|
dateTimeFormat
|
|
locale
|
|
timeZone
|
|
defaultVal
|
formattedTime
macro formattedTime
Renders a formatted time value (convenience wrapper).
The locale and timeZone (explicit or from context) should not resolve to null/empty;
if they do a log warning is printed.
Parameters
date
|
|
dateTimeFormat
|
|
locale
|
|
timeZone
|
|
defaultVal
|
formatDate
function formatDate
Formats a date.
The result is auto-HTML-escaped (where applicable); use #rawString to prevent.
The locale and timeZone (explicit or from context) should not resolve to null/empty;
if they do a log warning is printed.
Parameters
date
|
|
dateTimeFormat
|
|
locale
|
|
timeZone
|
|
dateType
|
Implemented as transform.
formatDateTime
function formatDateTime
Formats a date-time value.
The locale and timeZone (explicit or from context) should not resolve to null/empty;
if they do a log warning is printed.
Parameters
date
|
|
dateTimeFormat
|
|
locale
|
|
timeZone
|
formatTime
function formatTime
Formats a time value.
The locale and timeZone (explicit or from context) should not resolve to null/empty;
if they do a log warning is printed.
Parameters
date
|
|
dateTimeFormat
|
|
locale
|
|
timeZone
|
getHeadingElemSpecFromStyleStr
function getHeadingElemSpecFromStyleStr
Parses a complex style string meant to describe a markup element and styles, notably heading,
and converts to a hash of values.
containerElemType:containerClass;elemType:class;param1=val1,param2=val2
"h" and "heading" elem types support + notation for relative, and for these types
a level and relLevel are extracted.
Note that the class portions may be prefixed with "+" as well for append-not-replace logic.
Usage Examples
h3 h3:headingclass h+3:headingclass div:divclass;h+3:headingclass div:divclass;h+3:headingclass;consumeLevel=true
Parameters
styleStr
|
|
containerStyleStr
|
|
allowedHeadingElemTypes
|
|
allowedElemTypes
|
|
allowedContainerElemTypes
|
|
cacheId
|
extractPrefixedStyleNamesWithInt
function extractPrefixedStyleNamesWithInt
Helper method that can extract style names by prefix with int value suffix from style strings.
Parameters
style
|
(required) CSS Style/classes string |
prefixMap
|
((map), required) Map of CSS class prefixes to result names |
Return Value
a map of result names to integer values.
limitStrValToItems
function limitStrValToItems
Ensures that the given string value is contained in a field items list,
by only returning the value if it is in fact contained or void (missing value) otherwise.
items
parameter for field types select
, radio
or checkbox
.
If the value is matched, the value itself is returned; otherwise void (no result) is returned.
This should always be combined with one of the missing value Freemarker operators (??, !).
The value and item values automatically get the #rawString operation applied (along with coercion to string);
however, the original value is returned and not the raw one.
for performance and other reasons it is usually best to have a groovy script do this, but this is a frequently needed operation.
Parameters
value
|
((string), required) Value to check |
items
|
((list), required) Field items list, a list of maps, each map containing a value keyAlternatively, this may be a map, in which case the map keys are checked instead. |
key
|
(string, default: value) The name of the key to check for each map entry in the items list |
Return Value
the original value if it matched an item, or void if no item was matched (for use with missing value operator).
saveCurrentContainerSizes
function saveCurrentContainerSizes
This records current container (grid) sizes into a global stack
Every push should be followed by a pop.
This function is generally framework-agnostic and size-key agnostic.
Parameters
sizes
|
((map), required) Map of size names to integer values Typically, this will be (e.g.): {"large":12, "medium":12, "small":12} but can be anything (the methods in this file do not care). |
saveCurrentContainerSizesFromStyleStr
function saveCurrentContainerSizesFromStyleStr
Same as saveCurrentContainerSizes but tries to extract the container sizes from a style string.
class name strings (except for @cell which supports columns/small/medium/large args).
For this method to work, the framework-/theme-specific code must override the abstract
function parseContainerSizesFromStyleStr.
Parameters
style
|
(required) Style string containing grid size classes |
unsetCurrentContainerSizes
function unsetCurrentContainerSizes
Required call at container close following a saveCurrentContainerSizesXxx call at container open.
Parameters
parseContainerSizesFromStyleStr
function parseContainerSizesFromStyleStr
(abstract/placeholder)
ABSTRACT. This function should be overridden by a framework-specific implementation that parses the
container sizes from a class names string.
Parameters
style
|
(required) Style string containing grid size classes |
Return Value
a map of size names to integer values.
getCurrentContainerSizes
function getLastContainerSizes
Gets the last set of size values set by saveCurrentContainerSizes.
Parameters
getAllContainerSizes
function getAllContainerSizes
Gets a list of maps describing all (parent) container sizes nesting the current container
and the current container size (if was added).
Parameters
getAbsContainerSizeFactors
function getAbsContainerSizeFactors
Returns a map of container size factors.
{"large":n1, "medium":n2, "small":n3}
where n1, n2, n3 are floating-point (NOT integer) values calculated from the combination of all
grid sizes of all the current parent containers.
The above is only an example; this method is framework-agnostic.
These numbers can be used to approximate the current absolute column width in grid sizes,
in the absence of interfering CSS. It will only be useful if the parent containers save their
sizes in the stack using saveCurrentContainerSizesFromStyleStr or saveCurrentContainerSizes, and pop appropriately.
Requires framework-specific logic.
For this method to work, the framework-/theme-specific code must override the abstract
function evalAbsContainerSizeFactors.
ALTERNATIVELY, the framework-/theme-specific code may override getAbsContainerSizeFactors
if more specific parameters are needed.
The calculated factors are saved in their own stack and recalculated only when the main stack changes.
The cached factors are also passed to evalAbsContainerSizeFactors so it may exploit them,
but evalAbsContainerSizeFactors will never be called if the last container's factors were already
calculated (simple optimization). If need to bypass caching for some reason, theme
would have to override getAbsContainerSizeFactors (not recommended).
Parameters
maxSizes
|
((int)|(map), default: 0) Max container sizes (grid size) This is can a map of per-key max container sizes OR a single number giving max size for all keys (usually same in most frameworks) OR zero to mean use defaults. |
Return Value
((map)) a map of container size names to floating-point values
evalAbsContainerSizeFactors
function evalAbsContainerSizeFactors
(abstract/placeholder)
ABSTRACT. This function should be overridden by a framework-specific implementation that evals container
size factors.
Parameters
sizesList
|
((list), required) List of hashes describing all (known) parent and current container sizes
NOTE:
Entries may be empty and should be skipped. |
maxSizes
|
(default: 0) See #getAbsContainerSizeFactors maxSizes parameter |
cachedFactorsList
|
((list), default: -empty-) List of cached factor results, of same size and order as sizesList Each entry corresponds to the container at same index as the sizes in sizesList. If an entry is boolean, then a factor was not (yet) calculated for that container. |
Return Value
a map of size names to float values.
CONTEXT AND SYSTEM UTILITIES
Context and system utilities.
getRenderContextType
function getRenderContextType
Tries to figure out if this is web render, email, or other general.
Parameters
getRenderPlatformType
function getRenderPlatformType
html, xml, etc.; best-effort.
Parameters
getDefaultScipioLibLocation
function getDefaultScipioLibLocation
Returns a scipio library location.
this is currently render context-unaware
Returns void if nothing.
Parameters
libName
|
(variables|template, required)
|
renderPlatformType
|
((string), default: default) Platform type Caller should use #getRenderPlatformType(). |
renderContextType
|
((string), default: general) Render context type Caller should use #getRenderContextType(). |
getMacroLibraryLocationStaticFromResources
function getMacroLibraryLocationStaticFromResources
Gets a lib location from a theme resources variable which contains an expression, which can be either a straight component:// location
meant as "general" context and for "html" and "default" platforms, or a EL-defined map
${['[platform]':'component://...', ...]} e.g. ${[''html':'component://...', 'xml':'component://...', 'default':'component://...']}
Intended for use with VT_STL_VAR_LOC, VT_STL_TMPLT_LOC and variants.
Checks the resourceNames in the given order.
"default" is a special map key; should be avoided.
Parameters
renderPlatformType
|
|
resources
|
|
resourceNames...
|
runService
function runService
Runs a service synchronously, after automatically making the context valid.
It is generally discouraged to use heavy service calls in FreeMarker templates, but this
utility can be used to make such code safer.
As with other advanced functions, this function can take either 1-3 positional parameters (name, context)
OR a single args map.
Usage Examples
${(runService("getPartyNameForDate", {"partyId":userLogin.partyId!}).fullName)!} ${(runService("getPartyNameForDate", {"partyId":userLogin.partyId!}, true).fullName)!} ${(runService("getPartyNameForDate", {"partyId":userLogin.partyId!}, true, "null").fullName)!"ERROR"} ${(runService({"name":"getPartyNameForDate", "ctx":{"partyId":userLogin.partyId!}, "newTrans":true, "exMode":"error"}).fullName)!}
Parameters
args
|
|
ctx
|
((map), default: -empty map with context userLogin, locale, timeZone) The service context (This is parameter index 1 ( ctx ) when using positional arguments)This context is automatically populated with userLogin , locale andtimeZone from the environment context (the screen render map stack),unless this ctx already contains these keys or inclSysCtx is set to false.It is automatically passed through DispatcherContext.makeValidContext .
|
newTrans
|
((boolean), default: false) Whether to require a new transaction or not (requireNewTransaction) (This is parameter index 2 ( newTrans ) when using positional arguments)When services return errors during screen renders, the screen render transaction is aborted; setting this parameter to true prevents service errors from affectingthe screen render.
NOTE:
You may often want to use newTrans=true if you need to preventerrors from interfering with renderer. For legacy/compatibility/performance reasons, the newTrans default must remain false. |
exMode
|
(exmap|error|empty|null|throw, default: exmap) What to do on exceptions (except for validation exceptions) (This is parameter index 3 ( exMode ) when using positional arguments)Any of the following values may be set, which will apply the specified behavior for all excepts except for service validation exceptions ( org.ofbiz.service.ServiceValidationException ),which are always thrown:
In addition, you may add one of the following suffixes:
NOTE:
The reason the default is exmap (rather than the more convenient errorMap )is that it is not safe to assume exception messages and service error messages are both displayable to users - exception messages are generally completely inappropriate for display.
NOTE:
You may often want to use newTrans=true if you need to preventerrors from interfering with renderer. For legacy/compatibility/performance reasons, the newTrans default must remain false.
NOTE:
This only concerns literal service exceptions (ServiceValidationException, GenericServiceException, etc.); it does NOT handle regular service errors or failures, which are simply returned in a map result, as usual for services. |
name/args
|
(required) The service name to invoke OR a map of arguments (This is parameter index 0 ( args ) when using positional arguments)
|
inclEnvCtx
|
((boolean), default: true) Whether to automatically include the fields userLogin , locale and timeZone from the environment context (the screen render map stack). |
Return Value
The service result OR void/missing if the service threw an exception.
History
Added for 2.0.0.
Implemented as transform.
UTILITY CLASSES
Any class may be accessed using Static["my.package.com.ClassName"].myMethod(...)
,
but a few very common ones may be accessed (through FreeMarker beans) and their methods invoked using its class name only:
- Debug (org.ofbiz.base.util.Debug)
- UtilDateTime (org.ofbiz.base.util.UtilDateTime)
- UtilFormatOut (org.ofbiz.base.util.UtilFormatOut)
- UtilHttp (org.ofbiz.base.util.UtilHttp)
- UtilMisc (org.ofbiz.base.util.UtilMisc)
- UtilNumber (org.ofbiz.base.util.UtilNumber)
- StringUtil (org.ofbiz.base.util.StringUtil) (NOTE: The method wrapString is obsolete and replaced by #rawString function)
The return values are subject to screen auto-html-escaping, so depending on the case,
you may need to use #rawString.
Usage Examples
${Debug.logInfo("Logging from layoutdemo.ftl using Debug", "LayoutDemo.ftl")!"(see log)"} ${UtilDateTime.nowAsString()!"ERROR"} ${UtilFormatOut.formatPrice(234.33)!"ERROR"} ${UtilHttp.getCombinedMap(request)?size} ${UtilMisc.toMap("key1", "value1", "key2", "value2").key2!"ERROR"} ${UtilNumber.safeAdd(1, 2)!"ERROR"}
(No public definitions in this section)
DEV UTILITIES
For development and debugging purposes.
printVars
macro printVars
Iterates over all variable attributes & functions and prints in table.
since is in utilities.ftl, keep generic and check platform.
Usage Examples
<@printVars />
Parameters
var
|
((object), default: context) Var to be printed |
platform
|
((boolean)|html|..., default: true) The target platform (HTML, etc.) If true, looks up current render. |
maxDepth
|
((int), default: 5) Max depth, to prevent endless recursions |
utilCache
macro utilCache
Wraps a content element in a specific, custom cache. Can be used to Wrap freemarker content that is not often changed for
a faster processing time.
Usage Examples
<@utilCache cacheName="custom.ftl.filename" key="cacheKey"> // Static code </@utilCache>
Parameters
cacheName
|
((String)) Name of the cache to be used. Example "custom.ftl.filename" |
key
|
((String)) cache key value |
sizeLimit
|
((int), default: 0) Max depth, to prevent endless recursions |
maxInMemory
|
((int), default: 0) Max depth, to prevent endless recursions |
expireTime
|
((int), default: 1000) Max depth, to prevent endless recursions |
useSoftReference
|
((boolean), default: true) cache key soft reference |