go-twig/parse_apply.go
semihalev b44bad903b Implement spaceless filter and apply tag
1. Added spaceless filter that removes whitespace between HTML tags
2. Implemented {% apply filter %} ... {% endapply %} tag
3. Updated spaceless tag to use the spaceless filter internally
4. Fixed endverbatim tag handling
5. Added tests for all new functionality

The apply tag allows applying filters to blocks of content, which is the
modern recommended approach in Twig, replacing the deprecated spaceless tag.

🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
2025-03-11 17:28:57 +03:00

55 lines
1.8 KiB
Go

package twig
import (
"fmt"
)
func (p *Parser) parseApply(parser *Parser) (Node, error) {
// Get the line number of the apply token
applyLine := parser.tokens[parser.tokenIndex-2].Line
// Parse the filter name
if parser.tokenIndex >= len(parser.tokens) || parser.tokens[parser.tokenIndex].Type != TOKEN_NAME {
return nil, fmt.Errorf("expected filter name after apply tag at line %d", applyLine)
}
filterName := parser.tokens[parser.tokenIndex].Value
parser.tokenIndex++
// Expect the block end token
if parser.tokenIndex >= len(parser.tokens) ||
(parser.tokens[parser.tokenIndex].Type != TOKEN_BLOCK_END &&
parser.tokens[parser.tokenIndex].Type != TOKEN_BLOCK_END_TRIM) {
return nil, fmt.Errorf("expected block end token after apply filter at line %d", applyLine)
}
parser.tokenIndex++
// Parse the apply body
applyBody, err := parser.parseOuterTemplate()
if err != nil {
return nil, err
}
// Expect endapply tag
if parser.tokenIndex >= len(parser.tokens) || parser.tokens[parser.tokenIndex].Type != TOKEN_BLOCK_START {
return nil, fmt.Errorf("expected endapply tag at line %d", applyLine)
}
parser.tokenIndex++
// Expect 'endapply' token
if parser.tokenIndex >= len(parser.tokens) || parser.tokens[parser.tokenIndex].Type != TOKEN_NAME || parser.tokens[parser.tokenIndex].Value != "endapply" {
return nil, fmt.Errorf("expected 'endapply' at line %d", applyLine)
}
parser.tokenIndex++
// Expect block end token
if parser.tokenIndex >= len(parser.tokens) ||
(parser.tokens[parser.tokenIndex].Type != TOKEN_BLOCK_END &&
parser.tokens[parser.tokenIndex].Type != TOKEN_BLOCK_END_TRIM) {
return nil, fmt.Errorf("expected block end token after endapply at line %d", applyLine)
}
parser.tokenIndex++
// Create apply node (no arguments for now)
return NewApplyNode(applyBody, filterName, nil, applyLine), nil
}