Skip to content

Add center filter #179

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 2, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ More detailed examples and features description can be found in the documentatio
## Current Jinja2 support
Currently, Jinja2C++ supports the limited number of Jinja2 features. By the way, Jinja2C++ is planned to be a full [jinja2 specification](http://jinja.pocoo.org/docs/2.10/templates/)-conformant. The current support is limited to:
- expressions. You can use almost every expression style: simple, filtered, conditional, and so on.
- the big number of filters (**sort, default, first, last, length, max, min, reverse, unique, sum, attr, map, reject, rejectattr, select, selectattr, pprint, dictsort, abs, float, int, list, round, random, trim, title, upper, wordcount, replace, truncate, groupby, urlencode, capitalize, escape, tojson, striptags**)
- the big number of filters (**sort, default, first, last, length, max, min, reverse, unique, sum, attr, map, reject, rejectattr, select, selectattr, pprint, dictsort, abs, float, int, list, round, random, trim, title, upper, wordcount, replace, truncate, groupby, urlencode, capitalize, escape, tojson, striptags, center**)
- the big number of testers (**eq, defined, ge, gt, iterable, le, lt, mapping, ne, number, sequence, string, undefined, in, even, odd, lower, upper**)
- the number of functions (**range**, **loop.cycle**)
- 'if' statement (with 'elif' and 'else' branches)
Expand Down
1 change: 1 addition & 0 deletions src/filters.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ std::unordered_map<std::string, ExpressionFilter::FilterFactoryFn> s_filters = {
{"batch", FilterFactory<filters::Slice>::MakeCreator(filters::Slice::BatchMode)},
{"camelize", FilterFactory<filters::StringConverter>::MakeCreator(filters::StringConverter::CamelMode)},
{"capitalize", FilterFactory<filters::StringConverter>::MakeCreator(filters::StringConverter::CapitalMode)},
{"center", FilterFactory<filters::StringConverter>::MakeCreator(filters::StringConverter::CenterMode)},
{"default", &FilterFactory<filters::Default>::Create},
{"d", &FilterFactory<filters::Default>::Create},
{"dictsort", &FilterFactory<filters::DictSort>::Create},
Expand Down
3 changes: 2 additions & 1 deletion src/filters.h
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,8 @@ class StringConverter : public FilterBase
WordCountMode,
WordWrapMode,
UnderscoreMode,
UrlEncodeMode
UrlEncodeMode,
CenterMode
};

StringConverter(FilterParams params, Mode mode);
Expand Down
16 changes: 16 additions & 0 deletions src/string_converter_filter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,9 @@ StringConverter::StringConverter(FilterParams params, StringConverter::Mode mode
case TruncateMode:
ParseParams({{"length", false, static_cast<int64_t>(255)}, {"killwords", false, false}, {"end", false, std::string("...")}, {"leeway", false}}, params);
break;
case CenterMode:
ParseParams({{"width", false, static_cast<int64_t>(80)}}, params);
break;
default: break;
}
}
Expand Down Expand Up @@ -368,6 +371,19 @@ InternalValue StringConverter::Filter(const InternalValue& baseVal, RenderContex
return str;
});
break;
case CenterMode:
result = ApplyStringConverter(baseVal, [this, &context](auto srcStr) -> TargetString {
auto width = ConvertToInt(this->GetArgumentValue("width", context));
auto str = sv_to_string(srcStr);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think, it should be additional trimming added at this point. Now you doesn't count the spaces which already present at the beginning or at the end of the string,

Copy link
Contributor Author

@morenol morenol Nov 2, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you sure about that?

I tested this and it seems that it is not trimming those whitespaces:

from jinja2 import Environment

HTML = """
{{ 'x' | center(width=5) }}
{{ '  x' | center(width=5) }}
"""

def print_html_doc():
    print (Environment().from_string(HTML).render())
print_html_doc()

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok. You're right. Thank you!

auto string_length = static_cast<long long int>(str.size());
if ( string_length >= width )
return str;
auto whitespaces = width - string_length;
str.insert(0, (whitespaces + 1) / 2, ' ');
str.append(whitespaces / 2, ' ');
return TargetString(std::move(str));
});
break;
default:
break;
}
Expand Down
7 changes: 7 additions & 0 deletions test/filters_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -564,3 +564,10 @@ INSTANTIATE_TEST_CASE_P(Striptags, FilterGenericTest, ::testing::Values(
InputOutputPair{"'&amp;&apos;&gt;&lt;&quot;&#39;\"&#34;' | striptags | pprint", "'&\'><\"\'\"\"'"},
InputOutputPair{"'&#34;&#39;' | striptags | pprint", "'\"\''"}));


INSTANTIATE_TEST_CASE_P(Center, FilterGenericTest, ::testing::Values(
InputOutputPair{" 'x' | center | pprint", "' x '"},
InputOutputPair{" 'x' | center(width=5) | pprint", "' x '"},
InputOutputPair{" 'x' | center(width=0) | pprint", "'x'"},
InputOutputPair{" ' x' | center(width=5) | pprint", "' x '"}
));