* Demonstrate using callbacks instead of CsvTemplate class, * and performing record filtering outside of template. */
| 48 | * and performing record filtering outside of template. |
| 49 | */ |
| 50 | void printClassics(const FlashString& templateSource, Format::Formatter& formatter) |
| 51 | { |
| 52 | // The CSV data source |
| 53 | CSV::Reader csv(new FileStream(Filename::classics_csv)); |
| 54 | |
| 55 | // Use a regular SectionTemplate class to process the template |
| 56 | SectionTemplate tmpl(new FSTR::Stream(templateSource)); |
| 57 | |
| 58 | // We're going to filter the data based on publication year |
| 59 | String year_filter("1996"); |
| 60 | // Provide this to the template so it can show it in the header |
| 61 | tmpl.setVar(_F("year_filter"), year_filter); |
| 62 | // Improve speed by pre-fetching the filter column index |
| 63 | unsigned yearColumn = csv.getColumn(_F("bibliography.publication.year")); |
| 64 | |
| 65 | // Set up callback to handle fetching/filtering records |
| 66 | tmpl.onNextRecord([&]() -> bool { |
| 67 | if(tmpl.sectionIndex() == 1) { |
| 68 | while(csv.next()) { |
| 69 | // Could also use a more generic (but slower) approach: |
| 70 | // if(year_filter == tmpl.getValue("bibliography.publication.year")) |
| 71 | |
| 72 | if(year_filter == csv.getValue(yearColumn)) { |
| 73 | return true; |
| 74 | } |
| 75 | } |
| 76 | return false; |
| 77 | } |
| 78 | return tmpl.recordIndex() < 0; |
| 79 | }); |
| 80 | |
| 81 | // Set up callback to fetch values from CSV record |
| 82 | tmpl.onGetValue([&](const char* name) -> String { |
| 83 | String s = csv.getValue(name); |
| 84 | formatter.escape(s); |
| 85 | return s; |
| 86 | }); |
| 87 | |
| 88 | // Dump result to terminal |
| 89 | Serial.copyFrom(&tmpl); |
| 90 | } |
| 91 | |
| 92 | } // namespace |
| 93 |
no test coverage detected