{"id":22114071,"url":"https://github.com/carlcs/craft-helpers","last_synced_at":"2025-07-25T08:31:24.209Z","repository":{"id":62499646,"uuid":"59723350","full_name":"carlcs/craft-helpers","owner":"carlcs","description":"Helpers plugin for Craft CMS","archived":false,"fork":false,"pushed_at":"2017-07-24T00:18:19.000Z","size":426,"stargazers_count":60,"open_issues_count":0,"forks_count":2,"subscribers_count":5,"default_branch":"master","last_synced_at":"2024-04-24T20:27:18.393Z","etag":null,"topics":["craft-plugin","craftcms"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/carlcs.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-05-26T05:47:09.000Z","updated_at":"2024-04-24T20:27:18.394Z","dependencies_parsed_at":"2022-11-02T09:45:56.509Z","dependency_job_id":null,"html_url":"https://github.com/carlcs/craft-helpers","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carlcs%2Fcraft-helpers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carlcs%2Fcraft-helpers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carlcs%2Fcraft-helpers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carlcs%2Fcraft-helpers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/carlcs","download_url":"https://codeload.github.com/carlcs/craft-helpers/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227544347,"owners_count":17785198,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["craft-plugin","craftcms"],"created_at":"2024-12-01T11:08:42.181Z","updated_at":"2024-12-01T11:08:42.821Z","avatar_url":"https://github.com/carlcs.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Helpers plugin for Craft CMS\n\nA collection of Twig functions.\n\n## Installation\n\nThe plugin is available on Packagist and can be installed using Composer. You can also download the [latest release][1] and copy the files into craft/plugins/helpers/.\n\n```\n$ composer require carlcs/craft-helpers\n```\n\n  [1]: https://github.com/carlcs/craft-helpers/releases/latest\n\n## File Helpers\n\nThe plugin provides functions, which allow to read and convert JSON, YAML, CSV and PHP file contents. Using the `readText` or `inline` function you can read an entire file into a string.\n\nAll functions take a `path` argument, this can be either a relative or absolute path, or full URL to the file. A relative path is interpreted as relative to the web root by default, but this can be changed with the `basePath` config setting.\n\nHere are some ideas for what you can do with reading files:\n\n- read SVG files or “above-the-fold” CSS files and inline them into your templates\n- read documents written in markdown that you version control in Git\n- read mock data from JSON or YAML files for prototyping\n- read Element API endpoints without Ajax requests\n- read mapping tables for all sorts of things (keywords to element IDs, keywords to common sets of Atomic CSS classes, …)\n\n#### readJson( path )\n\nReads a JSON file, parses and converts its contents.\n\n- **`path`** (required) – The path to the file to read.\n\n```twig\n{% for article in readJson('https://example.com/api/news') %}\n    {{ article.body }}\n{% endfor %}\n```\n\n#### readYaml( path )\n\nReads a YAML file, parses and converts its contents.\n\n- **`path`** (required) – The path to the file to read.\n\n```twig\n{% set c = readYaml('tachyons/base.yaml') %}\n\u003cimg class=\"{{ c.img.avatar }}\" src=\"http://tachyons.io/img/logo.jpg\" alt=\"avatar\"\u003e\n\n{# outputs \"br-100 pa1 ba b--black-10 h3 w3\" #}\n```\n\n#### readCsv( path )\n\nReads a CSV file, parses and converts its contents.\n\n- **`path`** (required) – The path to the file to read.\n- **`associative`** (default `true`) – Whether an associative array should be returned for each row. The keys are provided from the first CSV row.\n\n```twig\n{% for customer in readCsv('data/customers.csv') %}\n    {{ customer['First Name'] }}\n{% endfor %}\n\n{# outputs \"Paul Clara Max Thomas Simone\" #}\n```\n\n#### readPhp( path )\n\nExecutes a PHP file’s return statement and returns the value.\n\n- **`path`** (required) – The path to the file to read.\n\n```twig\n{% for element in readPhp('data/elements.php') %}\n    {{ element.getUrl() }}\n{% endfor %}\n```\n\n#### readText( path )\n\nReads a file’s contents into a string. The plugin also provides an alias for this function with `inline( path )`.\n\n- **`path`** (required) – The path to the file to read.\n\n```twig\n{{ readText('data/notes.md')|md }}\n```\n\n```twig\n{{ inline('assets/svg/logo.svg') }}\n```\n\n```twig\n{% set data = inline(url('api/elements.json')) %}\n\u003cvue-component :data=\"{{ data }}\"\u003e\u003c/vue-component\u003e\n```\n\n## String Helpers\n\n#### truncate( length, suffix, preserve )\n\nTruncates a string to a given length.\n\n- **`length`** (default `30`) – The number of characters, beyond which the text should be truncated.\n- **`suffix`** (default `'…'`) – The string to be appended if truncating occurs.\n- **`preserve`** (default `true`) – Ensures that the filter doesn’t split words.\n\n```twig\n{{ 'This is some very long text and it is causing a lot of problems.'|truncate(30) }}\n\n{# outputs \"This is some very long text…\" #}\n```\n\n#### truncateHtml( length, suffix, preserve )\n\nA version of the `truncate` filter that is capable of handling HTML as an input string. `truncateHtml` closes HTML tags, if they’d be cut off by the truncation. Please note that its performance is worse than the normal `truncate` filter, so only use it when you need to.\n\n- **`length`** (default `30`) – The number of characters, beyond which the text should be truncated.\n- **`suffix`** (default `'…'`) – The string to be appended if truncating occurs.\n- **`preserve`** (default `true`) – Ensures that the filter doesn’t split words.\n\n```twig\n{{ 'This is some \u003cstrong\u003every long text and it is causing a lot of problems\u003c/strong\u003e.'|truncateHtml(30) }}\n\n{# outputs \"This is some \u003cstrong\u003every long text and\u003c/strong\u003e…\" #}\n```\n\n#### highlight( terms, format )\n\nHighlights given terms in a text.\n\n- **`terms`** (required) – A term or an array of terms that will be searched.\n- **`format`** (default `'\u003cmark\u003e\\1\u003c/mark\u003e'`) – The replacement string with a backreference to the found term. The default string can be overridden with the `highlightFormat` config setting.\n\n```twig\n{% set terms = 'we craf'|split(' ') %}\n{{ 'We just installed Craft!'|highlight(terms) }}\n\n{# outputs \"\u003cmark\u003eWe\u003c/mark\u003e just installed \u003cmark\u003eCraf\u003c/mark\u003et!\" #}\n```\n\n#### sentenceList( and, separator )\n\nGenerates a comma separated list from an array of strings, where the last two strings are joined with “and”.\n\n- **`and`** (default `', and '`) – The separator between the last two strings (translatable using [translation files][2]).\n- **`separator`** (default `', '`) – The separator between the other strings.\n\n```twig\n{% set names = ['Patrick', 'Clarisse', 'Caitlin', 'Danny', 'Loretta'] %}\n{{ names|sentenceList }}\n\n{# outputs \"Patrick, Clarisse, Caitlin, Danny, and Loretta\" #}\n```\n\n  [2]: https://craftcms.com/support/static-translations\n\n#### titleize( ignore )\n\nReturns a string with the first letter of each word capitalized.\n\n- **`ignore`** (default `['the', 'to', ...]`) – A list of words which should not be capitalized. The default list can be overridden with the `titleizeIgnore` config setting.\n\n```twig\n{{ 'i like to watch television'|titleize }}\n\n{# outputs \"I Like to Watch Television\" #}\n```\n\n#### collapseWhitespace\n\nTrims the string and replaces consecutive whitespace characters with a single space. This includes tabs and newline characters, as well as multibyte whitespace such as the thin space and ideographic space.\n\n```twig\n{{ '     where that  extra whitespace  might come from? '|collapseWhitespace }}\n\n{# outputs \"where that extra whitespace might come from?\" #}\n```\n\n#### stripWords( wordlist, ignoreCase )\n\nReturns the input string stripped from all words of a given list of words.\n\n- **`wordlist`** (required) – The array of words that should get stripped from the input string.\n- **`ignoreCase`** (default `true`) – Controls whether case is ignored or respected.\n\n```twig\n{% set string = 'In theory it removes both the A and AN, but not the THE.' %}\n{{ string|stripWords(['a', 'an']) }}\n\n{# outputs \"In theory it removes both the and , but not the THE.\" #}\n```\n\n#### stripPunctuation\n\nReturns the input string stripped from all punctuation.\n\n```twig\n{% set string = 'In theory it removes .,:;*# but not ßøü.' %}\n{{ string|stripPunctuation }}\n\n{# outputs \"In theory it removes but not ßøü\" #}\n```\n\n#### htmlEntityDecode\n\nReturns the input string with all HTML entities converted to their applicable characters.\n\n```twig\n{% set string = 'Ein Anf\u0026uuml;hrungszeichen ist \u0026lt;b\u0026gt;fett\u0026lt;/b\u0026gt' %}\n{{ string|htmlEntityDecode }}\n\n{# outputs \"Ein Anführungszeichen ist \u003cb\u003efett\u003c/b\u003e\" #}\n```\n\n## Number Helpers\n\n#### numbersToWords( locale )\n\nConverts a number to its word representation. The filter uses the Numbers_Words library to generate the output. Have a look at its documentation for a [list of supported languages][5].\n\n- **`locale`** (default `en_US`) – The language name abbreviation to set the ouput language.\n\n```twig\n{{ 42|numbersToWords('de') }}\n\n{# outputs \"zweiundvierzig\" #}\n```\n\n#### currencyToWords( locale, currency, decPoint)\n\nConverts a currency value to word representation. The filter uses the Numbers_Words library to generate the output. Have a look at its documentation for a [list of supported languages][5] and currency symbols.\n\n- **`locale`** (default `en_US`) – The language name abbreviation to set the ouput language.\n- **`currency`** (default `''`) – The international currency symbol to set the ouput currency.\n- **`decPoint`** (default `null`) – The separator for the decimal point.\n\n```twig\n{{ 1700.99|currencyToWords('en_US', 'EUR') }}\n\n{# outputs \"one thousand seven hundred euros ninety-nine euro-cents\" #}\n```\n\n  [5]: https://github.com/pear/Numbers_Words\n\n#### numeralSystem( numeralSystem, zero )\n\nConverts a number (arabic numeral system) to a representation of that number in another numeral system. If applied to a rational number (float), the filter rounds it to the closest integer first.\n\n- **`numeralSystem`** (required) – The numeral system the number gets converted to. You can convert to the roman numberal system (`'roman'`, `'upperRoman'` or `'lowerRoman'`) or to the alphabetical equivalent to the input number (`'alpha'`, `'upperAlpha'` or `'lowerAlpha'`).\n- **`zero`** (default `-1`) – Maps all negative numbers and zero. Setting this argument to `-1` gives you a decimal number to alphabetical character mapping like so: `-1` → `-B`, `0` → `-A`, `1` → `A`. Any other argument value other than `-1` or `1` does only map `0` to this value (i.e. `0` → `myZero`) and leaves negative number untouched.\n\n```twig\n{{ 42|numeralSystem('roman') }}\n\n{# outputs \"XLII\" #}\n```\n\n#### unitPrefix( system, decimals, trailingZeros, decPoint, thousandsSep, unitSep)\n\nFormats a number with unit prefixes.\n\n- **`system`** (default `decimal`) – Either a string (e.g. \"decimal\") to use a predefined configuration or an array of custom settings.\n- **`decimals`** (default `1`) – The number of decimal points.\n- **`trailingZeros`** (default `false`) – Whether to show trailing zeros.\n- **`decPoint`** (default `'.'`) – The separator for the decimal point.\n- **`thousandsSep`** (default `''`) – The thousands separator.\n- **`unitSep`** (default `' '`) – The separator between number and unit.\n\n```twig\n{{ 72064|unitPrefix }}\n\n{# outputs \"72.1 k\" #}\n```\n\n#### fractionToFloat( precision )\n\nConverts a fraction to a decimal number.\n\n- **`precision`** (default `4`) – The precision (number of digits after the decimal point) the returned value gets rounded to.\n\n```twig\n{{ '2/3'|fractionToFloat }}\n\n{# outputs \"0.6667\" #}\n```\n\n#### floatToFraction( tolerance )\n\nConverts a decimal number to a fraction.\n\n- **`tolerance`** (default `0.001`) – The allowed tolerance for the fraction calculation. So, for example, `0.7143` gets converted to `5/7` instead of `7138/9993`.\n\n```twig\n{{ 0.7143|floatToFraction }}\n\n{# outputs \"5/7\" #}\n```\n\n## Miscellaneous Helpers\n\n#### randomString( length, extendedChars )\n\nGenerates a random string of a given length.\n\n- **`length`** (default `36`) – The length of the generated string.\n- **`extendedChars`** (default `false`) – Whether to use an extended set of characters.\n\n```twig\n{{ randomString(6) }}\n\n{# outputs \"mRU1wI\" #}\n```\n\n#### md5( string )\n\nGenerates the md5 hash of a string.\n\n- **`string`** (required) – The string to generate the hash from.\n\n```twig\n{% set string = 'Lorem ipsum dolor sit amet.' %}\n{{ string|md5 }}\n\n{# outputs \"eb76f38646cca9420296bfc6731f94b5\" #}\n```\n\n#### json_decode( assoc, depth, options )\n\nDecodes a JSON string.\n\n- **`assoc`** (default `false`) – Whether objects should be converted into associative arrays.\n- **`depth`** (default `512`) – The recursion depth.\n- **`options`** (default `null`) – Bitmask of JSON decode options.\n\n```twig\n{% set json = '{\"beers\":[\"Alpirsbacher Klosterbräu\",\"Rothaus Tannenzäpfle\",\"Neumarkter Lammsbräu\"],\"whiskeys\":null}' %}\n{% set drinks = json|json_decode() %}\n\n{{ drinks.beers[1] }}\n\n{# outputs \"Rothaus Tannenzäpfle\" #}\n```\n\n#### setNotice( message )\n\nStores a notice in the user’s flash data.\n\n- **`message`** (required) – The message.\n\n```twig\n{% do setNotice('My short message.') %}\n{{ craft.session.getFlash('notice') }}\n\n{# outputs \"My short message.\" #}\n```\n\n#### setError( message )\n\nStores an error message in the user’s flash data.\n\n- **`message`** (required) – The message.\n\n```twig\n{% do setError('Do panic!') %}\n{{ craft.session.getFlash('error') }}\n\n{# outputs \"Do panic!\" #}\n```\n\n## Settings\n\nYou can override plugin defaults with a helpers.php config file, which you need to create in your craft/config/ folder.\n\n```php\n\u003c?php\n\nreturn [\n    'basePath' =\u003e getenv('BASE_PATH') ?: $_SERVER['DOCUMENT_ROOT'],\n    'highlightFormat' =\u003e '\u003cmark\u003e\\1\u003c/mark\u003e',\n    'titleizeIgnore' =\u003e ['at', 'by', 'for', 'in', 'of', 'on', 'out', 'to', 'the'],\n];\n```\n\n#### basePath\n\nThe `basePath` is used by the `inline` and file reading functions. The default setting uses the value of your `BASE_PATH` environment variable if you have that set, otherwise falls back your the web root. You can override it with something like, for example `CRAFT_CONFIG_PATH.'data/'`.\n\n#### highlightFormat\n\nA setting for the `highlight` filter, which defines how matched terms are replaced. The term itself is available from the `\\1` backreference.\n\n#### titleizeIgnore\n\nList of words which should not be capitalized by the `titleize` filter.\n\n## Requirements\n\n- PHP 5.4+\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcarlcs%2Fcraft-helpers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcarlcs%2Fcraft-helpers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcarlcs%2Fcraft-helpers/lists"}