hughperkins / Jinja2CppLight

(very) lightweight version of Jinja2 for C++

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Any chance for {if}/{endif} support?

dertuxmalwieder opened this issue · comments

I'd love to replace my blog software's current templating engine (based on NLTemplate) by a more common approach, e.g. yours (because I already know Jinja). The one big feature missing is {%if ... %} support for conditional template blocks.

Any chance you'd add that? :-)

You probably need to write this :-P

The sourcecode is fairly short. As long as you limit the scope of what you are trying to do to as small as possible, should take ~8 hours?

You can use the for as a guide. You'll need to copy and hack the For class: https://github.com/hughperkins/Jinja2CppLight/blob/master/src/Jinja2CppLight.h#L125-L156

class ForSection : public ControlSection {
public:
    int loopStart;
    int loopEnd;
    std::string varName;
    int startPos;
    int endPos;
    std::string render( std::map< std::string, Value *> &valueByName ) {
        std::string result = "";
//        bool nameExistsBefore = false;
        if( valueByName.find( varName ) != valueByName.end() ) {
            throw render_error("variable " + varName + " already exists in this context" );
        }
        for( int i = loopStart; i < loopEnd; i++ ) {
            valueByName[varName] = new IntValue( i );
            for( size_t j = 0; j < sections.size(); j++ ) {
                result += sections[j]->render( valueByName );
            }
            delete valueByName[varName];
            valueByName.erase( varName );
        }
        return result;
    }
    //Container *contents;
    virtual void print( std::string prefix ) {
        std::cout << prefix << "For ( " << varName << " in range(" << loopStart << ", " << loopEnd << " ) {" << std::endl;
        for( int i = 0; i < (int)sections.size(); i++ ) {
            sections[i]->print( prefix + "    " );
        }
        std::cout << prefix << "}" << std::endl;
    }
};

... and add some code here https://github.com/hughperkins/Jinja2CppLight/blob/master/src/Jinja2CppLight.cpp somehow. (theres only like ~250 lines in this second file).

OK, thank you. I'll consider that. (Planned for some time next year.) :)

I have a templating engine for c++ that uses a lua engine https://github.com/hughperkins/luacpptemplater It is pretty full-featured. The syntax is about as close as one can get to jinja2, within the constraint that it's running using lua. I use it a lot. I'm fairly happy with it.

Hmm, having Lua as a dependency...

Thanks though. I'll play with it. :-)

lua is inside the library. its 46kb. you wouldnt notice it was there, unless I told you.

Oh, nice. Bookmarked!