IF Statements

The %IF% construct gives Foswiki the power to include content in topics based on the value of simple expressions.

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, then whatever is in the THEN and ELSE parameters will already have been expanded by the time the condition is actually evaluated. The standard Format Tokens 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 name 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 ").

Examples

1. Macro defined or not

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

2. Compare macro definition

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

3. URL parameter

%IF{
   "defined 'search'"
   then="Search: $percentURLPARAM{search}$percent"
   else="No search passed in"
}%

4. Range test on URL parameter

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

5. Text comparison of URL parameter

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

6. Configuration item set or not (item must be one of {ScriptSuffix}, {LoginManager}, {AuthScripts}, {LoginNameFilterIn}, {AdminUserLogin}, {AdminUserWikiName}, {SuperAdminGroup}, {UsersTopicName}, {AuthRealm}, {MinPasswordLength}, {Register}{AllowLoginName}, {Register}{EnableNewUserRegistration}, {Register}{NeedVerification}, {Register}{RegistrationAgentWikiName}, {AllowInlineScript}, {DenyDotDotInclude}, {UploadFilter}, {NameFilter}, {AccessibleCFG}, {AntiSpam}{EmailPadding}, {AntiSpam}{HideUserDetails}, {AntiSpam}{RobotsAreWelcome}, {Stats}{TopViews}, {Stats}{TopContrib}, {Stats}{TopicName}, {UserInterfaceInternationalisation}, {UseLocale}, {Site}{Locale}, {Site}{CharSet}, {DisplayTimeValues}, {DefaultDateFormat}, {Site}{LocaleRegexes}, {UpperNational}, {LowerNational}, {PluralToSingular}, {EnableHierarchicalWebs}, {WebMasterEmail}, {WebMasterName}, {NotifyTopicName}, {SystemWebName}, {TrashWebName}, {SitePrefsTopicName}, {LocalSitePreferences}, {HomeTopicName}, {WebPrefsTopicName}, {UsersWebName}, {TemplatePath}, {LinkProtocolPattern}, {NumberOfRevisions}, {MaxRevisionsInADiff}, {ReplaceIfEditedAgainWithin}, {LeaseLength}, {LeaseLengthLessForceful}, {Plugins}{WebSearchPath}, {PluginsOrder}, {Cache}{Enabled}, {Validation}{Method}, {Register}{DisablePasswordConfirmation})

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

7. Plugin enabled test

TablePlugin is %IF{
   "context TablePluginEnabled"
   then="enabled"
   else="disabled"
}%.
expands to:
Table Plugin is enabled.

8. Check access permissions

You %IF{"'%TOPIC%' allows 'change'" then="can" else="cannot"}% change this topic.
You %IF{"'Sandbox.TestTopic' allows 'change'" then="can" else="cannot"}% change Sandbox.TestTopic.
You %IF{"'Sandbox' allows 'change'" then="can" else="cannot"}% change Sandbox web
expands to:
You cannot change this topic. You can change Test Topic?. You can change Sandbox web

9. Check topic existance

Topic Sandbox.TestTopic %IF{"istopic 'Sandbox.TestTopic'" then="exists" else="does not exist"}%
Web Sandbox.TestTopic %IF{"isweb 'Sandbox'" then="exists" else="does not exist"}%
expands to:
Topic Test Topic? does not exist Web Test Topic? exists

10. Group membership

You are %IF{
   "'%USERNAME%' ingroup 'AdminGroup'"
   then="an admin"
   else="a normal user"
}% 
expands to:
You are a normal user

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

Context identifiers

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 Command And CGIScripts)
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
changes in changes script (see Command And CGIScripts)
command_line the running script was run from the command line, and not from CGI
diff in rdiff script (see Command And CGIScripts)
edit in edit script (see Command And CGIScripts)
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
login and logon in login / logon script (see Command And CGIScripts)
manage in manage script (see Command And CGIScripts)
mirror if this is a mirror
new_topic if the topic doesn't already exist
oops in oops script (see Command And CGIScripts)
preview in preview script (see Command And CGIScripts)
register in register script (see Command And CGIScripts)
rename in rename script (see Command And CGIScripts)
resetpasswd in resetpasswd script (see Command And CGIScripts)
rss if this is an RSS skin rendering
save in save script (see Command And CGIScripts)
search in search script (see Command And CGIScripts)
statistics in statistics script (see Command And CGIScripts)
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 Command And CGIScripts)
view in view script (see Command And CGIScripts)
viewfile in viewfile script (see Command And CGIScripts)
rest in rest script (see Command And CGIScripts)
registration_supported registration is supported by the current User Mapper?
registration_enabled set if {Register}{EnableNewUserRegistration} is on, and registrationis supported
passwords_modifyable set if the password manager supports changing the password / email

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. Other extensions may set additional context identifiers.

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 Spread Sheet Plugin.

Query syntax

Note that while the query syntax 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:

Examples

Display the value of a form field if the topic has form field "Summary":
%FORMFIELD{
   "%IF{
      "'%TOPIC%'/Summary"
      then="Summary"
   }%"
}%
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%.WebHome'/lc(text)~'*welcome*'"
   then="contains 'welcome'"
}%