How to render view to open at anchor id

2019-09-14 18:33发布

Does anyone know if it's possible to render a view to open at an anchor tag in the middle of a page?

I want index.html to open at id="xyz".

This is my Controller code:

View::renderTemplate('Folder/index.html', [
        'array' => $array
    ]);

This throws an error:

View::renderTemplate('Folder/index.html#xyz', [
        'array' => $array
    ]);

标签: twig
1条回答
相关推荐>>
2楼-- · 2019-09-14 19:37

This is not possible, but you can use this solution with javascript.

Add the anchor on the page with the twig template. If the javascript find the ID, it redirects the nativator to the anchor without reloading the page.

{% block body %}
   <h2 id="goTo">Lorem Ipsum</h2>
{% endblock %}

{% block javascripts %}
    <script>
        document.addEventListener("DOMContentLoaded", function(event) {
            if(document.getElementById("goTo")){
                location.href = "#goTo"
            }
        });
    </script>
{% endblock %}

If you want redirect with an HTTP 301/302 code and anchor you can see _fragment https://symfony.com/blog/new-in-symfony-3-2-routing-improvements

查看更多
登录 后发表回答