IF statements

The %IF% macro gives you the ability to test for macro values, URL parameters, access permissions, topic existence and more.

Syntax

%IF{"CONDITION" then="THEN" else="ELSE"}%

In the example above, if CONDITION evaluates to TRUE, then THEN will be included in the topic; otherwise ELSE will be included.

Note that because of the way Foswiki evaluates, whatever is in the THEN and ELSE parameters will already have been expanded by the time the condition is actually evaluated. The standard FormatTokens can be used in the THEN and ELSE parameters when you need to delay evaluation of (for example) a macro.

The basic syntax of a condition is the same as the syntax used for queries, with the addition of the following special operators:

context True if the current context is set (see below)
allows 'X' allows 'Y' is true if web/topic 'X' exists and allows access mode 'Y' for the current user. Web access rights are only checked if there is no topic called 'X'.
istopic istopic 'X' is true if topic 'X' exists
isweb isweb 'X' is true if web 'X' exists
ingroup 'X' ingroup 'Y' is true if user 'X' is in group 'Y'. 'X' can be a login username or a WikiName.
defined True if a preference setting or URL parameter of this name is defined.
isempty True if a preference setting, URL parameter or session variable of this name has an empty value. It is equivalent to the expression (defined(x) || $x='')
$ expands a URL parameter or macro name. Plugin handlers are not called. You can pass a limited subset of parameters to macros by enclosing the parameter string in single quotes; for example, $'MACRO{value}'. The 'MACRO{value}' string may not contain quotes: ' or ".

The %IF% statement is deliberately kept simple. In particular, note that there is no way to conditionally execute a Set statement. If you need more sophisticated control over formatting, then consider using the SpreadSheetPlugin.

Macros

Test if macro is defined

%IF{"defined MACRO" then="THEN" else="ELSE"}%

Example:
%IF{
   "defined WIKINAME"
   then="WIKINAME is defined"
   else="WIKINAME is not defined"
}%

Compare macro definition

%IF{"$MACRO='VALUE'" then="THEN" else="ELSE"}%

Example:
You are %IF{
   "$WIKINAME='WikiGuest' and not defined 'OPEN_DAY'"
   then="not"
}% allowed to
%IF{
   "context view"
   then="view"
   else="edit"
}% this Foswiki today.

URL parameters

Test if URL param is passed

%IF{"defined PARAM" then="THEN" else="ELSE"}%

Example:
%IF{
   "defined search"
   then="Search:%URLPARAM{"search"}%"
   else="No search passed in"
}%

Note that macro URLPARAM is evaluated before the IF macro, therefore the expression does not need to be escaped.

Range test on URL parameter

%IF{"$PARAM < NUMBER" then="THEN" else="ELSE"}%

Example:
URL param t is %IF{
   "0 < $t and $t < 1000"
   then="in"
   else="out of"
}% range.

Text comparison of URL parameter

%IF{"$PARAM='VALUE'" then="THEN" else="ELSE"}%
or
%IF{"$'URLPARAM{PARAM}'='VALUE'" then="THEN" else="ELSE"}%

Example:
%IF{
   "$scope='text'"
   then="Plain text search"
}%

or

%IF{
   "$'URLPARAM{scope}'='text'"
   then="Plain text search"
}%

URL parameter test

Be careful when you test for an empty value: if the URL parameter is not defined (not passed in the URL), the outcome might not be what you expected. Use the parameter test to check your assumptions.

Test IF query no param empty param param=text
    test: no param test: empty param test: param=text
is defined defined scope      
is empty $scope=''      
is not empty $scope!=''      
has value text $scope='text'"      

Reset test

INCLUDE parameters

%IF{"$PARAM" then="THEN" else="ELSE"}%

Parameters that are passed to the INCLUDE macro are evaluated the same as URL parameters. Combining those may lead to unexpected results!

Example:
%INCLUDE{"%TOPIC%" section="people" name="Barry"}%
%STARTSECTION{"people"}%
%IF{"$name" then="%name%"}%
%ENDSECTION{"people"}%

INCLUDE parameter test

%INCLUDE{"%TOPIC%" section="includetest" name="Barry"}%

Test IF query param 'name' Result param 'name' IF query param 'yo' Result param 'yo'
is defined defined name true defined yo false
is empty $name='' false $yo='' false NOTE: value is undefined, so not empty
is not empty $name!='' true $yo!='' false NOTE: value is undefined, so not 'not empty'
has value Barry $name='Barry' true $yo='Barry' false

%STARTSECTION{"includetest"}%
%TABLE{databg="#ffffff" headeralign="left"}%
| *Test* \
| *IF query param 'name'* \
| *Result param 'name'* \
| *IF query param 'yo'* \
| *Result param 'yo'* |
| is defined \
| =defined name= \
| %IF{"defined name" then='true'}% \
| =defined yo= \
| %IF{"defined yo" else='false'}% |
| is empty \
| =$name=''= \
| %IF{"$name=''" else='false'}% \
| =$yo=''= \
| %IF{"$yo=''" else="false %RED%NOTE: value is undefined, so not empty%ENDCOLOR%"}% |
| is not empty \
| =$name!=''= \
| %IF{"$name!=''" then='true'}% \
| =$yo!=''= \
| %IF{"$yo=''" else="false %RED%NOTE: value is undefined, so not \'not empty\'%ENDCOLOR%"}% |
| has value =Barry= \
| =$name='Barry'= \
| %IF{"$name='Barry'" then='true'}% \
| =$yo='Barry'= \
| %IF{"$yo='Barry'" else='false'}% |
%ENDSECTION{"includetest"}%

Configuration values

Configuration items are defined in configure. You cannot see the value of a configuration item, you can only test if the item is set, or test the value against a string.

Items must be one of {AccessControlACL}{EnableDeprecatedEmptyDeny}, {AccessibleCFG}, {AdminUserLogin}, {AdminUserWikiName}, {AntiSpam}{EmailPadding}, {AntiSpam}{EntityEncode}, {AntiSpam}{HideUserDetails}, {AntiSpam}{RobotsAreWelcome}, {AttachmentNameFilter}, {AuthRealm}, {AuthScripts}, {Cache}{Enabled}, {DefaultDateFormat}, {DefaultUrlHost}, {DenyDotDotInclude}, {DisplayTimeValues}, {EnableEmail}, {EnableHierarchicalWebs}, {FormTypes}, {HomeTopicName}, {LeaseLength}, {LeaseLengthLessForceful}, {LinkProtocolPattern}, {LocalSitePreferences}, {LoginNameFilterIn}, {MaxRevisionsInADiff}, {MinPasswordLength}, {NameFilter}, {NotifyTopicName}, {NumberOfRevisions}, {PluginsOrder}, {Plugins}{WebSearchPath}, {PluralToSingular}, {Register}{AllowLoginName}, {Register}{Approvers}, {Register}{DisablePasswordConfirmation}, {Register}{EnableNewUserRegistration}, {Register}{NeedApproval}, {Register}{NeedVerification}, {Register}{RegistrationAgentWikiName}, {ReplaceIfEditedAgainWithin}, {SandboxWebName}, {ScriptSuffix}, {ScriptUrlPath}, {Site}{Locale}, {SitePrefsTopicName}, {Stats}{TopContrib}, {Stats}{TopicName}, {Stats}{TopViews}, {SuperAdminGroup}, {SystemWebName}, {TemplateLogin}{AllowLoginUsingEmailAddress}, {TemplatePath}, {TrashWebName}, {UploadFilter}, {UseLocale}, {UserInterfaceInternationalisation}, {UsersTopicName}, {UsersWebName}, {Validation}{Method}, {WebMasterEmail}, {WebMasterName}, {WebPrefsTopicName}.

Testing if item is set

%IF{"{CONFIGURATION}" then="THEN" else="ELSE"}%

Example:
User details are %IF{
   "{AntiSpam}{HideUserDetails}"
   then="hidden"
   else="shown"
}%

Testing the value of an item

%IF{"{CONFIGURATION}='VALUE'" then="THEN" else="ELSE"}%

Example:
Validation method is %IF{
   "{Validation}{Method}='strikeone'"
   then="'strikeone'"
   else="no 'strikeone'"
}%

Plugin states

%IF{"context PLUGINEnabled" then="THEN" else="ELSE"}%

Example:
TablePlugin is %IF{
   "context TablePluginEnabled"
   then="enabled"
   else="disabled"
}%.

Access permissions

%IF{"'SOME TOPIC' allows 'ACCESS'" then="THEN" else="ELSE"}%

Example:
You %IF{"'%TOPIC%' allows 'change'" then="can" else="cannot"}% change this topic.
You %IF{"'%SANDBOXWEB%.TestTopic' allows 'change'" then="can" else="cannot"}% change %SANDBOXWEB%.TestTopic.
You %IF{"'Sandbox' allows 'change'" then="can" else="cannot"}% change Sandbox web

Topic existence

%IF{"istopic 'SOME TOPIC'" then="THEN" else="ELSE"}%

Example:
Topic %SANDBOXWEB%.TestTopic %IF{"istopic '%SANDBOXWEB%.TestTopic'" then="exists" else="does not exist"}%.
Web %SANDBOXWEB% %IF{"isweb '%SANDBOXWEB%'" then="exists" else="does not exist"}%.

Group membership

To test if SOMEONE is in the GROUP:
%IF{"'SOMEONE' ingroup 'GROUP'" then="THEN" else="ELSE"}%

Or to test the currently logged in user for AdminGroup membership:
You are %IF{
   "$USERNAME ingroup 'AdminGroup'"
   then="an admin"
   else="a normal user"
}%

Context identifiers

%IF{"context CONTEXT" then="THEN" else="ELSE"}%

Context identifiers are used in Foswiki to label various stages of the rendering process. They are especially useful for skin authors to find out where they are in the rendering process. The following context identifiers are available:
id context
absolute_urls Set if absolute URLs are required
attach in attach script (see CommandAndCGIScripts)
authenticated a user is authenticated
body_text when the body text is being processed in a view (useful in plugin handlers)
can_login current environment supports login
can_render_meta set by CompareRevisionsAddOn Compare.pm
can_remember_login Template Login: Controls rendering of "remember login" checkbox.
no_auto_complete_login Template Login: Prevents browser from remembering password
changes in changes script (see CommandAndCGIScripts)
command_line the running script was run from the command line, and not from CGI
diff in rdiff script (see CommandAndCGIScripts)
edit in edit script (see CommandAndCGIScripts)
footer_text when the footer text is being processed in a view (useful in plugin handlers)
header_text when the header text is being processed in a view (useful in plugin handlers)
i18n_enabled when user interface I18N support is enabled (i.e., user can choose the language for UI)
inactive if active links such as 'edit' and 'attach' should be disabled
isadmin current user has admin rights
login and logon in login / logon script (see CommandAndCGIScripts)
manage in manage script (see CommandAndCGIScripts)
mandatoryfields if any fields in form have mandatory attribute.
mirror if this is a mirror
new_topic if the topic doesn't already exist
oops in oops script (see CommandAndCGIScripts)
passwords_modifyable when the PasswordManager is able to modify passwords (correct as spelled)
preview in preview script (see CommandAndCGIScripts)
register in register script (see CommandAndCGIScripts)
registration_supported registration is supported by the current user mapper
registration_enabled set if {Register}{EnableNewUserRegistration} is on, and registration is supported
rename in rename script (see CommandAndCGIScripts)
resetpasswd in resetpasswd script (see CommandAndCGIScripts)
rest in rest script (see CommandAndCGIScripts)
rss if this is an RSS skin rendering
save in save script (see CommandAndCGIScripts)
search in search script (see CommandAndCGIScripts)
static in a script that generates static content, such as PDF generation. Extensions should avoid rendering edit markup in this context.
statistics in statistics script (see CommandAndCGIScripts)
sudo_login if user is currently running with internal admin authority
SUPPORTS_PARA_INDENT render supports the paragraph indent syntax
SUPPORTS_PREF_SET_URLS Preferences can be set in the URL
textareas_hijacked provided for use by editors that highjack textareas, and want to signal this fact. This is used by skins, for example, so they can suppress extra controls when textareas have been hijacked.
upload in upload script (see CommandAndCGIScripts)
view in view script (see CommandAndCGIScripts)
viewfile in viewfile script (see CommandAndCGIScripts)

In addition there is a context identifier for each enabled plugin; for example, if GallousBreeksPlugin is installed and enabled, then the context ID GallousBreeksPluginEnabled will be set. JQueryPlugin sets a context for each enabled JQuery plugin, for example: LiveQueryEnabled, UI::DialogEnabled. Other extensions may set additional context identifiers.

Query syntax

%IF{"QUERY" then="THEN" else="ELSE"}%

Examples

Display the value of a form field if the topic has form field "Summary":
%FORMFIELD{
   "%IF{
      "'%TOPIC%'/Summary"
      then="Summary"
   }%"
}%
Note that while a query search can be used to access form fields, there are some contexts in which an IF statement may be used where there is no topic context, or the topic context is not what you want. In these cases you can use the / operator to indicate the name of the topic:

HELP The IF macro is expanded before FORMFIELD. Read more

Test if the topic has attachments:
%IF{
   "'%TOPIC%'/attachments"
   then="has attachments"
}%

Test if the topic has an attachment with 'receipt' or 'Receipt' in the name:
%IF{
   "'%TOPIC%'/attachments[lc(name)~'*receipt*']"
   then="has 'receipt' attachment"
}%

Test if a topic text contains a certain word:
%IF{
   "'%SYSTEMWEB%.%HOMETOPIC%'/lc(text)~'*welcome*'"
   then="contains 'welcome'"
}%
Topic revision: r1 - 22 Jan 2018, UnknownUser
This site is powered by FoswikiCopyright © by the contributing authors. All material on this site is the property of the contributing authors.
Ideas, requests, problems regarding Foswiki? Send feedback