1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| #include "HtmlTemplateLoader.h"
#include <QFile>
HtmlTemplateLoader::HtmlTemplateLoader()
{
}
void HtmlTemplateLoader::assign( const QString & TemplateVar, const QString & Value )
{
this->zVars[ TemplateVar ] = Value;
}
void HtmlTemplateLoader::assign( const QString & TemplateVar, int Value )
{
return this->assign( TemplateVar, QString::number( Value ) );
}
QString HtmlTemplateLoader::fetch( const QString & TemplateFilePath )
{
QString content;
// load the template content
QFile file( TemplateFilePath );
if ( file.open( QIODevice::ReadOnly ) )
{
content = QString::fromUtf8( file.readAll().data() );
file.close();
}
else
{
qCritical() << "Could not find file" << TemplateFilePath;
return QString::null;
}
// result
QString result;
result.reserve( content.length() + 100 );
// template vars replacement
int pos;
while ( ( pos = content.indexOf( "{{" ) ) != -1 )
{
// extract the variable name
int end = content.indexOf( "}}", pos + 2 );
if ( end == -1 )
{
qCritical() << "Invalid template var syntax in file"
<< TemplateFilePath;
return content;
}
QString varName = content.mid( pos + 2, end - pos - 2 ).simplified();
// find the value for this var
QString value;
QMap<QString, QString>::const_iterator i = this->zVars.find( varName );
if ( i == this->zVars.end() )
{
qWarning() << "Missing value for template variable" << varName;
}
else
{
value = *i;
}
// do the template var replacement
result.reserve( result.length() + value.length()
+ content.length() - end - 2 );
result += content.left( pos );
result += value;
// keep only the remaining content
content = content.mid( end + 2 );
}
result += content;
return result;
} |
Partager