Skip to content

Commit 9403660

Browse files
committed
directive: add support for regular expression custom directive.
Example: The custom directive {name: /\?(php|=).*/, start: '<', end: '>'} will match any directive with <?php ?> or <?= ?> pattern
1 parent 923b16a commit 9403660

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ Tag objects can contain three keys. The `tag` key takes the name of the tag as t
8282
### `directives`
8383
Type: `Array`
8484
Default: `[{name: '!doctype', start: '<', end: '>'}]`
85-
Description: *Adds processing of custom directives*
85+
Description: *Adds processing of custom directives. Note: The property ```name``` in custom directives can be ```String``` or ```RegExp``` type*
8686

8787
## License
8888

index.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,20 @@ function postHTMLParser(html, options) {
2929
var directives = options.directives || defaultDirectives;
3030
var last = bufArray.last();
3131

32+
var tagName;
3233
for (var i = 0; i < directives.length; i++) {
3334
var directive = directives[i];
3435
var directiveText = directive.start + data + directive.end;
36+
var isDirective = false;
3537

36-
if (name.toLowerCase() === directive.name) {
38+
tagName = name.toLowerCase();
39+
if ((directive.name instanceof RegExp) && directive.name.test(tagName)) {
40+
isDirective = true;
41+
} else if (tagName === directive.name) {
42+
isDirective = true;
43+
}
44+
45+
if (isDirective) {
3746
if (!last) {
3847
results.push(directiveText);
3948
return;

test/test.js

+9
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,15 @@ describe('PostHTML-Parser test', function() {
131131
expect(parser('<?php echo "Hello word"; ?>', customDirectives)).to.eql(['<?php echo "Hello word"; ?>']);
132132
});
133133

134+
it('should be parse regular expression directive', function() {
135+
var customDirectives = {directives: [
136+
{name: /\?(php|=).*/, start: '<', end: '>'}
137+
]};
138+
139+
expect(parser('<?php echo "Hello word"; ?>', customDirectives)).to.eql(['<?php echo "Hello word"; ?>']);
140+
expect(parser('<?="Hello word"?>', customDirectives)).to.eql(['<?="Hello word"?>']);
141+
});
142+
134143
it('should be parse directives and tag', function() {
135144
var customDirectives = {directives: [
136145
{name: '!doctype', start: '<', end: '>'},

0 commit comments

Comments
 (0)