Parse CSV file in template provide paginated results.
This plugin requires Craft CMS 3.0.0-beta.23 or later.
To install the plugin, follow these instructions.
-
Open your terminal and go to your Craft project:
cd /path/to/project
-
Then tell Composer to load the plugin:
composer require leaplogic/csv-parse
-
In the Control Panel, go to Settings → Plugins and click the “Install” button for CSV Parse.
The plugin is mean to parse a CSV file provided via an Asset then provide results as an array. You have the ability to filter or search the CSV file.
Make sure to provide an Asset input to add a CSV file to your CMS. The plugin will use this in the template to parse and provide an array of results.
{% set headers = craft.csvParse.headers(entry.csvInput.one()) %}
In this example we are pulling a url param to grab which page of entries to return.
{% set amount = 20 %}
{% set offset = craft.app.request.getParam('pg')|number_format * 20 %}
{% set entries = craft.csvParse.entries(entry.csv.one(), offset, amount) %}
{
'data' => Array,
'meta' => [
'total' => Number
]
}
{% macro table(items,headers) %}
<table>
<tr>
{% for item in headers %}
<th>{{ item }}</th>
{% endfor %}
</tr>
{% for item in items %}
<tr>
{% for col in item %}
<td>{{ col }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% endmacro %}
{% import _self as self %}
{{ self.table(entries.data, headers) }}
{% set total = entries.meta.total %}
{% set prevPg = craft.app.request.getParam('pg')|number_format - 1 == 0 ? 1 : craft.app.request.getParam('pg')|number_format - 1 %}
{% set nextPg = craft.app.request.getParam('pg')|number_format + 1 >= (total / amount)|round ? (total / amount)|round : craft.app.request.getParam('pg')|number_format + 1 %}
{% set filterType = craft.app.request.getParam('q') ? '&q=' ~ craft.app.request.getParam('q')|url_encode : craft.app.request.getParam('f') ? '&f=' ~ craft.app.request.getParam('f')|url_encode : '' %}
{% if total > amount %}
<div class="pagination">
<a href="?pg={{ prevPg }}{{ filterType }}">PREV</a>
<span>{{ craft.app.request.getParam('pg') ? craft.app.request.getParam('pg') : 1 }} / {{ (total / amount)|round }}</span>
<a href="?pg={{ craft.app.request.getParam('pg') ? nextPg : 2 }}{{ filterType }}">NEXT</a>
</div>
{% endif %}
Some things to do, and ideas for potential features:
- Release it
Brought to you by Leap Logic