Modx filters. Using if else conditions in MODx

Today useful article about phx filters and their modifiers MODX Revo with which you can manipulate the value of various tags right inside the templates.

Why are they needed?

phx modifiers make life easier for modx developers. Let's say we have a website with an image carousel (or a banner) that we need output only to home page . To do this, just put it in a separate chunk and then display it in the template using this construction

Where: 1 — home page id,
$carusel— a chunk with the carousel (banner) code.
Only full teapots are created new template, for the sake of a few lines of carousel code. I was like that too, in general, we don’t despair and implement phx into development.

Let's look at the above structure in more detail:

[[*id:is=`1`:then=`[[$carusel]]`]]

*id— displays id current page;

:is=`1`:then=

- checks if it is equal *id == 1? and if equal, then the contents are output then;
$carusel— displays the carusel chunk.

Instead of *id, you can use other fields, for example *template - will display the currently used template. Or you can check whether the TV field is filled in or not (let it be *keywords) and if it is filled, then display it. Let's look at this case in more detail. The standard markup is given:

Task: do not display this line if TV keywords are empty.
Solution.

[[*keywords:!empty=` `]]

Loads

You need to monitor the processing of modifiers; their thoughtless use will cause unnecessary loads. Let's go back to the carousel, this entry is read from left to right and MODH executes all nested conditions, regardless of whether the condition is true or not, whether the contents are displayed on the current page [[$carusel]], in any case, its contents will be processed. In this regard, it is more appropriate to rewrite the entry:

[[$caru[[*id:is=`1`:then=`sel`]]]]

In this case, the contents of the chunk $carusel, will be processed if the condition is met

*id:is=`1`

because running

[[*id:is=`1`:then=`sel`]]

and if the id of the current page is 1, the last thing that is processed is [[$carusel]], if id is not equal to 1 then − [[$caru]]. And if chunka $caru- if not in the elements, then there will be no load.

In general, the ideal output would look like this.

[[$[[*id:is=`1`:then=`carusel`]]]]

About how to properly integrate layout into modx revo I recommend reading here.

Note! You can combine as many modifiers as you like to suit the operating logic of the site components, but the main thing to remember is that their main essence is make development easier, and not complicate already complex tasks. Usually the most effective and effective way- this is the simplest, since the simpler and clearer the design, the easier it will be to work with it in the future. Below are the main modifiers that you can use for any MODH Revo tag.

Modifier chains

A good example chaining will format the date string to a different format, like this:

[[+mydate:strtotime:date=`%Y-%m-%d`]]

Direct access to the "modx_user_attributes" table in the database using output modifiers instead of a snippet can be done simply by using a modifier userinfo. Select the appropriate column from the table and specify it as an output modifier property, for example, like this:

Internal user key: [[!+modx.user.id:userinfo=`internalKey`]] Login: [[!+modx.user.id:userinfo=`username`]] Full name: [[!+modx.user .id:userinfo=`fullname`]] Role: [[!+modx.user.id:userinfo=`role`]] E-mail: [[!+modx.user.id:userinfo=`email`]] Phone: [[!+modx.user.id:userinfo=`phone`]] Mobile phone: [[!+modx.user.id:userinfo=`mobilephone`]] Fax: [[!+modx.user.id :userinfo=`fax`]] Birthday: [[!+modx.user.id:userinfo=`dob`:date=`%Y-%m-%d`]] Gender: [[!+modx.user .id:userinfo=`gender`]] Country: [[!+modx.user.id:userinfo=`country`]] State: [[!+modx.user.id:userinfo=`state`]] Zip code : [[!+modx.user.id:userinfo=`zip`]] Photo: [[!+modx.user.id:userinfo=`photo`]] Comment: [[!+modx.user.id:userinfo =`comment`]] Date last login: [[!+modx.user.id:userinfo=`lastlogin`:date=`%Y-%m-%d`]] Number of logins: [[!+modx.user.id:userinfo=`logincount`] ]

Pay special attention to the exclamation mark [[ ! +modx.user.id]]. It allows DO NOT cache output contents. Why should you not cache? Let's imagine it like this: there are 5 users on the site. The first user visited the page with the challenge:

Welcome, [[!+modx.user.id:userinfo=`username`]]!

As planned, this page displays a welcome message to the user. So, if the result is cached, then the first time you enter this page, the name of the user who just entered will be saved, and everyone else will be shown not their name, but the name of the user who entered this page first. To avoid this, we simply do not cache this tag using exclamation point before calling [[ ! +modx…

P.s.: Don't forget turn off caching tags where needed! To do this you need GET RID from exclamation marks ( ! ) . The results of most snippets can easily work from the cache. We'll look at it in the next lesson.

Filters in Revolution allow you to manipulate how certain tags are processed. They allow you to change values ​​right inside your templates.

Input filters

Currently, input filters are used in preparation for processing output filters. They are usually only used inside the MODX engine.

Output filters

In Revolution, output filters behave the same way as PHx in Evolution, only the filters are now built directly into the MODX engine. The syntax looks like this:

[]

Filters can be applied sequentially. To do this, write them in a row (from left to right):

[]

Filters can also be used to modify the output of snippets. The filter must be specified before all parameters (before the question mark):

[]

Output modifiers

The table shows some modifiers and examples of their use. In the examples, modifiers are applied to placeholders, but you should remember that they can be applied to any MODX tags. Make sure the tag you use outputs at least something that the modifier will process.

Conditional output modifiers

Modifier Description Usage example
if, input Pass arbitrary text as input for the next modifier [[*id:input=`[[+placeholder]]`:is=`1`:then=`Yes`:else=`No`]]
or OR [[+numbooks:is=`5`:or:is=`6`:then=`There are 5 or 6 books here`:else=`Not sure how many books`]]
and Combining multiple modifiers with a link AND [[+numbooks:gt=`5`:and:lt=`10`:then=`There are from 5 to 10 books here`:else=`There are either less than 5 or more than 10 books`]]
isequalto, isequal, equalto, equals, is, eq Compares the passed value with the set value. If the values ​​match, the value “then” is displayed, if not - “else” [[+numbooks:isequalto=`5`:then=`There are 5 books here`:else=`Not sure how many books`]]
notequalto, notequals, isnt, isnot, neq, ne Compares the passed value with the set value. If the values ​​do NOT match, the value "then" is displayed, if not - "else" [[+numbooks:notequalto=`5`:then=`Not sure how many books`:else=`There are 5 books`]]
greater thanorequalto, equalorgreaterthen, ge, eg, isgte, gte The same, only the condition is “Greater than or equal to” [[+numbooks:gte=`5`:then=`There are 5 books or more here`:else=`There are less than five books here`]]
isgreaterthan, greaterthan, isgt, gt The same, only the condition “Strictly more” [[+numbooks:gt=`5`:then=`There are more than five books here`:else=`There are 5 books or less`]]
equaltoorlessthan, lessthanorequalto, el, le, islte, lte The same, only the condition is “Less than or equal to” [[+numbooks:lte=`5`:then=`There are 5 books or less here`:else=`There are more than five books here`]]
islowerthan, islessthan, lowerthan, lessthan, islt, lt The same, only the condition “Strictly less” [[+numbooks:lte=`5`:then=`There are less than five books here`:else=`There are 5 books or more here`]]
hide Hides the element if the condition is true [[+numbooks:lt=`1`:hide]]
show Displays an element if a condition is true [[+numbooks:gt=`0`:show]]
then Used to create conditions [[+numbooks:gt=`0`:then=`Books in stock!`]]
else Used to create conditions (together with “then”) [[+numbooks:gt=`0`:then=`Books in stock!`:else=`Sorry, but everything is sold out.`]]
memberof, ismember, mo Checks whether the user is a member of the specified user group [[!+modx.user.id:memberof=`Administrator`]]

Modifiers for working with strings

Modifier Description Usage example
cat Adds a value after the tag [[+numbooks:cat=`books`]]
lcase, lowercase, strtolower Converts all letters to lowercase [[+title:lcase]]
ucase, uppercase, strtoupper Converts all letters to uppercase [[+headline:ucase]]
ucwords Capitalizes the first letter of words [[+title:ucwords]]
ucfirst Capitalizes the first letter in a string [[+name:ucfirst]]
htmlent, htmlentities Converts all characters to corresponding HTML entities [[+email:htmlent]]
esc, escape Safely escapes characters using regular expressions and `str_replace()`. Also escapes MODX tags. [[+email:escape]]
strip Replaces all hyphens, tabs, and any number of spaces with just one space [[+textdocument:strip]]
stripString Cuts the specified substring from a string [[+name:stripString=`Mr.`]]
replace Replaces substrings [[+pagetitle:replace=`Mr.==Mrs.`]]
striptags, stripTags, notags, strip_tags Cuts out all tags (allowed tags can be specified). Do not use for safety purposes. [[+code:strip_tags]]
len,length,strlen Prints the length of a string [[+longstring:strlen]]
reverse, strev Reverses a string character by character [[+mirrortext:reverse]]
wordwrap Inserts a line break after every nth character (words are not broken) [[+bodytext:wordwrap=`80`]]
wordwrapcut Inserts a line break after every nth character, even if this character is inside a word [[+bodytext:wordwrapcut=`80`]]
limit Prints a specified number of characters from the beginning of a line (default is 100) [[+description:limit=`50`]]
ellipsis Adds an ellipsis and truncates the line if it is longer than the specified number of characters (default is 100) [[+description:ellipsis=`50`]]
tag Shielding. Displays the element as it is, without the :tag. For use in documentation [[+showThis:tag]]
add, increment, incr Adds the specified number (default +1) [[+downloads:incr]] [[+blackjack:add=`21`]]
subtract, decrement, decr Subtracts the specified number (default -1) [[+countdown:decr]] [[+moneys:subtract=`100`]]
multiply, mpy Multiplies by the specified number (default *2) [[+trifecta:mpy=`3`]]
divide,div Divides by the specified number (default /2) [[+rating:div=`4`]]
modulus, mod Returns the modulus of a number (default: %2, returns 0 or 1) [[+number:mod]]
ifempty,default,empty,isempty Returns the modifier value if the tag value is empty [[+name:default=`anonymous`]]
notempty, !empty, ifnotempty, isnotempty Returns the modifier value if the tag value Not empty [[+name:notempty=`Hello [[+name]]!`]]
nl2br Replaces characters new line\n to the HTML br tag [[+textfile:nl2br]]
date Converts the timestamp to text according to the specified format (date format) [[+birthyear:date=`%Y`]]
strtotime Converts date as text to UNIX timestamp [[+thetime:strtotime]]
fuzzydate Accepts a timestamp and returns a date in the form "Today at 16:20 PM" [[+createdon:fuzzydate]]
ago Returns the number of seconds, minutes, weeks, or months that have passed since the date specified in the tag. [[+createdon:ago]]
md5 Creates an MD5 hash of a value [[+password:md5]]
cdata Wraps the output with CDATA tags [[+content:cdata]]
userinfo Returns the requested value from the user profile. User ID required [[!+modx.user.id:userinfo=`username`]]
isloggedin Returns 1 if the user is authorized in the current context [[!+modx.user.id:isloggedin:is=`1`:then=`Yes`:else=`No`]]
isnotloggedin Returns 1 if user Not authorized in the current context [[!+modx.user.id:isnotloggedin:is=`1`:then=`No`:else=`Yes`]]
urlencode Converts the value as a URL, that is, uses the PHP `urlencode()` function [[+mystring:urlencode]]
urldecode Converts the value as from a URL, that is, uses the PHP function `urldecode()` [[+myparam:urldecode]]

Modifiers for working with users must be called uncached so that each user sees the latest data.

Using Output Modifiers with Parameters

If a tag has parameters, then they must be written immediately after the modifier:

[[!getResources:default=`Sorry, nothing found`? &tplFirst=`blogTpl` &parents=`2,3,4,8` &tvFilters=`blog_tags==%[[!tag:htmlent]]%` &includeTVs=`1` ]]

Creating a Custom Modifier

Any snippet can be used as an output modifier. To do this, simply specify the snippet name instead of the modifier. For example, let's create a snippet [] that adds a certain number of exclamation points to the output:

[[*pagetitle:makeExciting=`4`]]

Such a tag call will pass the following parameters to the makeExciting snippet for processing:

Parameter Meaning Example value

Good health to all. In this article I will tell you how to make a document filter based on TV parameters on a website running Modx Revolution. We will use the snippet tagManager2 from Andchir. This snippet can work with several TVs at once, as well as with numerical data (in the form of a price) and a multiple list. We will analyze each of these examples further.

1. First you need to install tagManager2

To do this we go to Applications/Installer/

press the button "Download add-on" and enter in the search bar tagManager2

You also still need to install the snippet getPage and getProducts. Thus section "Package Management" should look like this (the translit snippet, by the way, is responsible for transliterating aliases into Latin)

Download, install packages and go to "System Settings"

2. Set up the tagManager2 snippet

IN System settings select the tag_manager2 section

We will see the filter settings options

Everything there is quite simple and clear, but still:

  • IN "Top Level Directory Resource ID" specify the id of the catalog template or category where products or pages will be filtered
  • IN "Additional multiple list delimiter" put the # sign. Below you will find out why it is needed
  • IN "TV or multiple list field names" register TV with a multiple list. I will show you how to create them below.
  • "Names of TV or fields with numerical values» - here you need to specify TV parameters, which will contain numbers. This is usually a price parameter. This filter will be displayed as a slider “from and to”
  • IN “Product Template IDs” we write down the ids of the pages that need to be filtered and to which the TV parameters specified above are attached
  • IN "Name of parameter set used for filtering" register catalog_filters. This template we will use in parameter templates getPage And getProducts
  • Register in “Snippet associated with a set of parameters” the name of the snippet that will display and paginate pages or products. Usually this getPage.

3. Create a set of catalog_filters parameters in getPage

Let's go to the getPage snippet

Go to the tab "Options" and press the button "Add parameter set". You can, of course, edit the existing one, but then there is a chance of overwriting the parameters that we will now create when updating getPage. If you are not going to update, you can just edit.

Edit existing parameters and assign values:

Create new parameters and assign values

The edited parameters will be displayed green, created - purple

4. Create or edit TV parameters for the filter

I created 3 TV parameters for example

I would like to draw special attention to the fact that you need to specify the Name (Title) of the TV parameter, otherwise it may simply not be displayed in the filter control module

​5.Create a chunk filtr_tpl

This chunk is responsible for outputting each individual result in getProducts

6. Create a structure in the document tree

For me it looks like this:

Our main page has ID 1, and products have template ID 1 (we have this in the tag_manager2 settings, if you have other values, don’t forget to change it in the settings)

7. Edit filters.js

Let's go to the address /assets/components/tag_manager2/js/web/filters.js and instead

Multitags: ["tags"],//Additional names. fields with multiple values

insert the code with our substituted values

Multitags: ["filtr1", "filtr2"],//Additional names. fields with multiple values

Everything here is extremely simple and clear. We inserted our tv fields with multiple values. In general, this is a config of all settings (but it’s better not to touch them without the permission of big guys, I mean the advice of the creators of the module)

8. Display the filter and filtering results

The filter itself

[]
[[+filters]]

Displaying results with pagination

[[!tmCatalog]]
    [[!+page.nav]]

Sorting results

9. Activate the filter

Now we just need to activate our filter. To do this we go to Applications/Filter Management.

Here you need to check the boxes next to each filter and click the button"Save" .

If you did everything correctly, the filter should work. That's all. If you have any questions, ask in the comments, I will try to answer. In general, here is the documentation for tagManager2 . Good luck in development. IN "Demo" one of my sites that implements a filter using tagManager2

Yes, another way to implement an Ajax filter on a website =)

Let's start with a simple display of a regular list of resources on the page. Be sure to ensure that AJAX pagination works properly, because we will not write our own mechanisms for working with AJAX, but will use the AJAX methods that are in pdoPage.

("!pdoPage" | snippet: [ "ajaxMode" => "default", "parents" => 0, "limit" => 3, "includeTVs" => "height,weight,speed_type,price", "tvPrefix" => "", "tpl" => "@INLINE

($pagetitle)

Weight: ($weight)

Height: ($height)

Type: ($speed_type)

", ]}
("page.nav" | placeholder)

For filters I will use this layout. But layout doesn’t play a special role here - the main thing is to specify the correct classes in the JS code.


The filter processing JS code looks something like this:

$(document).on("change keyup", "#filters input", function())( // Check that pdoPage is connected if (typeof(pdoPage) == "undefined") return; // Collect the values ​​of all filters in single array var fields = (); $.each($("#filters").serializeArray(), function())( // If the parameter is not an array (checkbox), then everything is simple if (this.name.indexOf( "")<= 0) { fields = this.value; } else { // Для чекбоксов посложнее var name = this.name.replace("",""); if (typeof(fields) == "undefined") { fields = ; } fields.push(this.value); } }); // И отправляем этот массив на сервер. $.post(document.location.href, { action: "filter", fields: fields, // Параметр hash - обязательный (он содержит настройки pdoPage) hash: pdoPage.configs.page.hash }, function(data) { // Просим pdoPage загрузить новый список ресурсов var tmp = document.location.href.split("?"); pdoPage.keys.page = 0; pdoPage.loadPage(tmp, pdoPage.configs.page); }); });
Already now, when you change the value of the filters, the list of resources will be updated. Now all that remains is to “explain” how to process filters. To do this, create a plugin for the event OnHandleRequest:

context->key == "mgr" || empty($_SERVER["HTTP_X_REQUESTED_WITH"]) || $_SERVER["HTTP_X_REQUESTED_WITH"] != "XMLHttpRequest") return; switch ($_POST["action"]) ( case "filter": $output = array("success" => false, "message" => ""); // Check that the hash has been received and the pdoPage parameters exist if ( isset($_POST["hash"]) && !empty($_POST["hash"]) && isset($_SESSION["pdoPage"][$_POST["hash"]]) && !empty($_SESSION[" pdoPage"][$_POST["hash"]])) ( $hash = (string) $_POST["hash"]; // Specify only TVs available for filtering $tvs = array("height","weight" ,"speed_type"); // Fill in the selection condition $where = array(); switch ($tv) ( case "price": // Example of processing checkboxes if (isset($_POST[ "fields"]["price"]) && !empty($_POST["fields"]["price"])) ( $where_price = ; foreach ($_POST["fields"]["price"] as $range ) ( $value = explode("-", $range); if (count($value) != 2) ( continue; ) $min = (int) $value; $max = (int) $value; $where_range = "CAST(`TVprice`.`value` AS DECIMAL(13,3)) >= " . $min; if ($max) ( $where_range .= " AND CAST(`TVprice`.`value` AS DECIMAL( 13.3))<= " . $max; } $where_price = "(" . $where_range . ")"; } $where = "(" . implode(" OR ", $where_price) . ")"; } break; default: if (isset($_POST["fields"][$tv]) && $_POST["fields"][$tv] !== "") { $where[$tv] = $_POST["fields"][$tv]; } break; } } // Добавляем это условие в параметры pdoPage "на лету" $_SESSION["pdoPage"][$hash]["where"] = $where; $output["message"] = $where; $output["success"] = true; } else { $output["message"] = "Error"; } echo $modx->toJSON($output); die(); break; default: break; )
Now our filters are working. The only thing is that pdoPage "doesn't know" what to show when no results are found. To take this case into account, let's create a file pdopage.custom.js and specify it in the parameter frontend_js:

("!pdoPage" | snippet: [ "ajaxMode" => "default", "frontend_js" => "/assets/components/pdotools/js/pdopage.custom.js", "parents" => 0, "limit" => 3, // ... )
In the standard code we will only add the condition else in case the response from the server is empty:

// ... pdoPage.loadPage = function (href, config, mode) ( // ... $.post(config["connectorUrl"], params, function (response) ( if (response && response["total" ]) ( // ... ) else ( // Add a condition else wrapper.find(rows).html("Nothing found"); wrapper.find(pagination).html(""); wrapper.removeClass(" loading"); wrapper.css((opacity: 1)); if (config["mode"] == "default") ( $("html, body").animate((scrollTop: wrapper.position(). top - 50 || 0), 0); // ...
This completes the simple AJAX filter.

In this article I would like to tell you about filters (modifiers) in MODx.

In principle, you can live without them, but knowing how and where they are used, the developer receives a powerful tool with which you can add small, but sometimes very useful logic to your site.

In this article I will talk about MODx Revolution. The ability to apply filters exists thanks to the PHx snippet, which by default is already built into the MODx Revolution core, but PHx is not included in the Evolution core, so it must be installed separately on Evo.

So, filters allow you to manipulate the data that is obtained as a result of parsing placeholders and tags. They provide an opportunity modify data directly in your templates.

The syntax for filters is as follows:

It’s very convenient that they can be arranged in chains:

At the same time, it is also possible to pass parameters to snippets. The main thing is that the filter is written between the snippet name and the question mark:

The following table lists some of the filters and example showing them application. Although the examples use a placeholder, filters can be applied to any MODx tag. Make sure that the placeholder actually returns something.

Conditional modifiers

ModifierDescriptionExample
or Can be used with string modifiers to create a logical AND relationship
and Can be used with string modifiers to create a logical "OR" relationship
isequalto, isequal, equalto, equals, is, eq Compares the output with the specified value and, if there is a match, continues parsing the tag. Used in conjunction with "then" and "else" [[+numbooks:isequalto=`5`:then=`There are 5 books!`:else=`Not sure how many books`]]
notequalto, notequals, isnt, isnot, neq, ne Compares the output with the specified value and, if it does not match, continues parsing the tag. Used in conjunction with "then" and "else" [[+numbooks:notequalto=`5`:then=`Not sure how many books`:else=`There are 5 books!`]]
greater thanorequalto, equalorgreaterthen, ge, eg, isgte, gte

Compares the output with the specified value and, if the output is greater than or equal to the passed value, continues parsing the tag. Used in conjunction with "then" and "else"

[[+numbooks:gte=`5`:then=`There are 5 books or more than 5 books`:else=`There are less than 5 books`]]
isgreaterthan, greaterthan, isgt, gt

Compares the output with a given value. If the output is larger, parsing continues. Used with "then" and "else"

[[+numbooks:gt=`5`:then=`There are more than 5 books`:else=`There are less than 5 books`]]
equaltoorlessthan, lessthanorequalto, el, le, islte, lte Compares the output with the specified value and, if the output is less than or equal to the passed value, continues parsing the tag. Used in conjunction with "then" and "else" [[+numbooks:lte=`5`:then=`There are 5 or less than 5 books`:else=`There are more than 5 books`]]
islowerthan, islessthan, lowerthan, lessthan, islt, lt Compares the output with a given value. If the output is less, parsing continues. Used with "then" and "else" [[+numbooks:lte=`5`:then=`Less than 5 books`:else=`More than 5 books`]]
hide Checks the preceding conditions. If they were true, hides the element. [[+numbooks:lt=`1`:hide]]
show Checks the preceding conditions. If they were true, displays the element. [[+numbooks:gt=`0`:show]]
then Used as a consequence of some condition [[+numbooks:gt=`0`:then=`Now available!`]]
else Used as a consequence of some condition. Used in conjunction with "then" [[+numbooks:gt=`0`:then=`Now available!`:else=`Sorry, currently sold out.`]]
memberof, ismember, mo Returns the result of checking whether a user belongs to a given group. [[+modx.user.id:memberof=`Administrator`]]

String modifiers

ModifierDescriptionExample
cat Appends the specified string to the output if the output is not empty. [[+numbooks:cat=` books`]]
lcase, lowercase, strtolower Converts all characters in a string to lowercase. Identical to PHP function strtolower [[+title:lcase]]
ucase, uppercase, strtoupper Converts all characters in a string to uppercase. Identical to PHP function strtoupper [[+headline:ucase]]
ucwords Converts the first letters of all words in a string to uppercase. Identical to PHP ucwords function [[+title:ucwords]]
ucfirst Converts the first letter of a string to uppercase. Identical to PHP function ucfirst [[+name:ucfirst]]
htmlent, htmlentities

Identical to the PHP htmlentities function. Uses the current value of the system parameter "modx_charset" with the ENT_QUOTES flag

[[+email:htmlent]]
esc,escape Safely mnemonizes characters using regular expressions and str_replace. Also understands [, ] and ` [[+email:escape]]
strip Replaces all line breaks, tabs, and multiple spaces with a single space. [[+textdocument:strip]]
stripString Removes the specified substring from a string. [[+name:stripString=`Mr.`]]
replace Replaces one substring with another. [[+pagetitle:replace=`Mr.==Mrs.`]]
striptags, stripTags, notags, strip_tags Removes all PHP and HTML tags except the specified one. Identical to the PHP strip_tags function [[+code:strip_tags=`

`]]

len,length,strlen Prints the length of the string. Identical to PHP strlen function [[+longstring:strlen]]
reverse, strev Identical to PHP function strrev [[+mirrortext:reverse]]
wordwrap Identical to the PHP wordwrap function. Takes the optimal value for setting the word wrap position. [[+bodytext:wordwrap=`80`]]
wordwrapcut Identical to PHP wordwrap function with word breaks. Takes the optimal value for setting the word wrap position. [[+bodytext:wordwrapcut=`80`]]
limit Limits (truncates) the length of a string in a specified number of characters. The default length limit is 100 characters. [[+description:limit=`50`]]
ellipsis Trims a string to the specified number of characters and adds an ellipsis. The default limit is 100 characters. [[+description:ellipsis=`50`]]
tag Displays the called element without :tag. Useful for documentation, for example, like mine =) [[+showThis]]
math Returns the result of calculations (not recommended because it creates a load on the processor)
add,increment,incr Returns a value incremented by a specified amount (by default, by one) [[+downloads:incr]]
[[+blackjack:add=`21`]]
subtract, decrement, decr Decrements the specified value from a value (default: -1) [[+countdown:decr]]
[[+moneys:subtract=`100`]]
multiply,mpy Returns the result of multiplication by a number (default: *2) [[+trifecta:mpy=`3`]]
divide,div Returns the result of division by a number (default: /2) 0 is not allowed. [[+rating:div=`4`]]
modulus, mod Returns the remainder of a division (Default: %2, returns 0 or 1) [[+number:mod]]
ifempty,default,empty,isempty Returns the given string if the output is empty. [[+name:default=`anonymous`]]
notempty, !empty, ifnotempty, isnotempty Returns the given string if the output is not empty. [[+name:notempty=`Hello [[+name]]!`]]
nl2br Identical to the PHP nl2br function. All line breaks are replaced by
[[+textfile:nl2br]]
date Identical to the PHP strftime function. The format is passed as a value. See Date Formats. [[+birthyear:date=`%Y`]]
strtotime Identical to the PHP strtotime function. Applies to dates only. See Date Formats. [[+thetime:strtotime]]
fuzzydate Returns the date in the format "today at 13:40", "yesterday at 18:40". [[+publishedon:fuzzydate]]
ago Returns the number of seconds, minutes, hours, weeks, etc. from the date to the current moment. Applies to dates only [[+createdon:ago]]
md5 Identical to the PHP md5 function. [[+password:md5]]
cdata Encloses a string in CDATA tags. [[+content:cdata]]
userinfo Returns the requested user data. Applies to user ID in MODx. The modifier contains the field that needs to be returned. [[+modx.user.id:userinfo=`username`]]
isloggedin Returns "true" if the user is authorized in this context. [[+modx.user.id:isloggedin]]
isnotloggedin Returns "true" if the user is authorized in this context [[+modx.user.id:isnotloggedin]]
urlencode Identical to PHP urlencode function [[+mystring:urlencode]]
urldecode Identical to PHP urldecode function [[+myparam:urldecode]]

Creating custom modifiers

Snippets can be used as modifiers. To do this, simply replace the name of the filter with the name of the snippet. For example, we have a snippet called "makeDownloadLink"

[[+file:makeDownloadLink=`notitle`]]

This call will pass the following parameters to the snippet:


The result will be what will be returned snippet.

Examples of use

Here is an example where the filters are called one after another. This example formats a date from a string to another format:

[[+mydate:strtotime:date=`%Y-%m-%d`]]

Direct access to the modx_user_attributes table from the database from the snippet can be replaced by simply using the userinfo modifier. To get the required field, you need to pass the name of the column from the database to the modifier parameters.

Internal key: [[!+modx.user.id:userinfo=`internalKey`]]

Username: [[!+modx.user.id:userinfo=`username`]]

Full name: [[!+modx.user.id:userinfo=`fullname`]]

Role: [[!+modx.user.id:userinfo=`role`]]

E-mail: [[!+modx.user.id:userinfo=`email`]]

Phone: [[!+modx.user.id:userinfo=`phone`]]

Mobile: [[!+modx.user.id:userinfo=`mobilephone`]]

Fax: [[!+modx.user.id:userinfo=`fax`]]

Date of birth: [[!+modx.user.id:userinfo=`dob`:date=`%Y-%m-%d`]]

Gender: [[!+modx.user.id:userinfo=`gender`]]

Country: [[+modx.user.id:userinfo=`country`]]

Region: [[+modx.user.id:userinfo=`state`]]

Postal code: [[+modx.user.id:userinfo=`zip`]]

Avatar: [[+modx.user.id:userinfo=`photo`]]

Share