Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
reuse content of part of url in html

i would like to reuse parts of the url in the content of the webpage

as example domain.com/specialist/brand/location/

where i want to reuse "brand" multiple times in the content of the webpage and also "location" multiple times in the content of the webpage.

first i tried it with variables url/?specialist=brand&bezorgen=city

but this does not work with the following method, because it renders them only once

i've tried the

<script>
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const specialist = urlParams.get('specialist');
    const bezorgen = urlParams.get('bezorgen');
    document.getElementById("specialist").innerHtml = specialist;
    document.getElementById("bezorgen").innerHtml = bezorgen;

</script>

and in the html

<span id=specialist></span>
<span id=bezorgen></span>

What would be the fastest way to get this working

technology = twig and js

Thanks in advance

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Twig

As you are using a custom framework I'd suggest you to mimick the app.request.get behavior that is available in Symfony.

First create a class that delivers the same logic

Request.php

class Request {
    public function __construct() {}

    public function get($key) {
        return isset($_GET[$key]) ? $_GET[$key] : null;
    }

    public function post($key) {
        return isset($_POST[$key]) ? $_POST[$key] : null;
    }

    public function url() {
        $http = 'http'.(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 's': '');
        return  $http.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    }
}

Register the class in twig

The easiest way to add an instance of the Request class is just to add it as a global

<?php
    ...
    $twig->addGlobal('app', [ 'request' => new Request(), ]);

Access the class inside a template

<p>this {{ app.request.get('brand') }} bike is pretty awesome and we can deliver this at {{ app.request.get('location') }}. This {{ app.request.get('brand') }} is really trustworthy</p>

mandatory note

Please be aware it is possible that clients will try to inject/generate unsafe output. However twig will prevent this as long as you don't mark the content as safe with e.g. the filter raw

about 4 years ago · Juan Pablo Isaza Relatório

0

Javascript

The problem with your javascript is probably because you are creating elements with the same id over and over again, which is why only the first element with the correct id will be replaced correctly

An easy solution would be to switch to classes

var foo = 'foo';
var bar = 'bar';

document.querySelectorAll('.foo').forEach(span => {
    span.innerHTML = foo;
});

document.querySelectorAll('.bar').forEach(span => {
    span.innerHTML = bar;
});
span {
    display: block;
}

span + span {
    margin: 10px 0 0 0;
}

span.foo {
    color: red;
}

span.bar {
    color: green;
}
<span class="foo"></span>
<span class="foo"></span>
<span class="bar"></span>
<span class="foo"></span>
<span class="foo"></span>
<span class="bar"></span>

about 4 years ago · Juan Pablo Isaza Relatório

0

I might be misunderstanding, but the OP seems to ask two things: (1) how to extract info from the url -- either from within the path or the query, (2) how to alter the dom with that info.

Looking at (1), you can get a lot of information from the expression new URL(window.location.href);

// using the path
// these window-named vars to simulate the browsers' window global
let windowA = {
  location: {
    href: "http://example.com/specialist/mybrand/mylocation"
  }
};
const urlA = new URL(windowA.location.href);
console.log(urlA.pathname.split('/').slice(-2));

// using the query
let windowB = {
  location: {
    href: "http://example.com/specialist/?brand=mybrand&location=mylocation"
  }
};
const urlB = new URL(windowB.location.href);
const params = [urlB.searchParams.get('brand'), urlB.searchParams.get('location')]
console.log(params);

Looking at (2), the OP code looks fine, except the div's ids need to be placed in quotes...

let _window = {
  location: {
    href: "http://example.com/specialist/mybrand/mylocation"
  }
};
const url = new URL(_window.location.href);
const components = url.pathname.split('/').slice(-2);

document.getElementById("brand").innerHTML = `<h1>${components[0]}</h1>`;
document.getElementById("location").innerHTML = `<h1>${components[1]}</h1>`;
<!-- notice the quoted id expressions -->
<div id="brand"></div>
<div id="location"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda