For a node application I have a list of uploaded files shown with Ractive which works great so far. One of the fields I use is the Filetype (in my Data stored as extension eg FileType: pptx
).
In my ractive Template I'd like to show a corresponding Image to the type of File uploaded for visual aid, but that tends to end in an endless if-statement.
So for now the template looks (simplified) like
'<span class="fa
{{#if FileType == "pptx" || FileType == "ppt" || FileType == "ppts" || //going on here forever}}
fa-file-powerpoint-o
{{elseif FileType == "xls" || FileType == "xlsx" || ...}}
fa-file-excel-o
//then the same follows for Videos, Word, pdf, ...
{{else}}
fa fa-file-o
{{/if}}
"></span>'
Does anybody know a decent way to shorten that horrible piece of code?
I think the easiest way would be to have a mapping of extension -> class stored in your data at eg ~/fileType
. So { ppt: 'fa-file-powerpoint-o', pptx: 'etc' }
could then be used in the template as class="fa {{~/fileType[FileType] || 'fa-file-o'}}"
.
You could shrink the data a bit by shipping a list of list of name -> type eg
const types = [[['ppt', 'pptx', 'ppty', 'pptz'],'fa-file-powerpoint-o'], [['exe'], 'fa-file-boom']]
const map = {};
types.forEach(entry => entry[0].forEach(extension => map[extension] = entry[1]));
this.set('fileType', map);
I would think the best way to tackle that particular problem is by using a database.
So you can add a record for a specified icon and assign multiple extensions to it. Then retrieve a dataset with all records and just loop through it and check for that field containing that extension.
And then of course you can set a 'default' record that will show a default icon.
And as a plus, if you only need to make one comparison, that logic execution can be handed off to the DBMS server in the SELECT query.
EDIT:
I realise now the 'database' would have to be client side.
So instead just use a xml file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.