Fixed #15053 -- Improved template extending algorithm.

What about simplyfying this whole if/else block to:
```python
extends_history = context.get(EXTENDS_CONTEXT_KEY, {})
```