Javascript variable in Django template

Asked

Viewed 588 times

0

Hello guys, good afternoon, I need to use a JS variable, being it the type Boolean in the Django template

but I don’t know how to do it.

Example of what I want to do:

<!DOCTYPE html>
<html>
    <body>
    <script>
        let showMessage = false;
    </script>
    {% if showMessage %}
         faça isso
    {% else %}
         faça aquilo
    {% endif %}
    </body>
</html>

I know that python is very simple, but I’m using a web service in JS

registrations.js:

// RETORNO DA API EM JSON - AUTOCOMPLETE DOS INPUT
let showMessage = false;

function callback(content) {
    if (!("erro" in content)) {
        const Inputs = document.querySelectorAll(`form input`);
        Inputs[2].value = (content.logradouro);
        Inputs[4].value = (content.complemento);
        Inputs[5].value = (content.bairro);
        Inputs[6].value = (content.localidade);
        Inputs[7].value = (content.uf);
    } else {
        formClean();
        showMessage = true;  <---- aqui que mudo o valor da variavel
    }
}
// FAZ BUSCA DO CEP - ONBLUR
function searchByCep() {
    const cep = document.querySelector(`#id_zip_code`);
    if (cep.value != "") {

        let script = document.createElement(`script`);
        script.src = 'https://viacep.com.br/ws/' + cep.value + '/json/?callback=callback';

        document.body.appendChild(script);
    }
};

  • And why don’t you use your own if javascript?

  • @Andersoncarloswoss why in case I want to display an error message when showMessage = true remembering that I want to use the variable in the Django template

  • 1

    But it doesn’t make sense. Python runs on the server, JS on the client. If you just want to display an error message when it is true, you can do this only with Javascript. Read about the concepts of client-side and server-side.

  • @Andersoncarloswoss understand that I could do it using document.createElement(), but in my opinion it would not be the best way to do it... but it was worth

  • 2

    It will only be easier if you set the value of the variable also by Python. Otherwise, how will it know the value? You will have to parse the HTML to be able to extract the information.

  • In the example code showMessage never changes. In real code what would change this value? Some Python variable or some jQuery action on the page?

  • @fernandosavio I edited the question to be easier to understand, I will try to use document.createElement(), but I am open to new knowledge

  • I would create an element intended only for feedback in Python and JS just change its content with innerHTML or affines and then make it visible. .

Show 3 more comments

1 answer

1

You can create an element that will only serve to show the error and leave it hidden with CSS. When there is an error just modify your content by JS and show it.

I made an example using fetch but the operation is the same, the callback function will perform when the request returns.

let cep = document.querySelector('#cep');
let dados = document.querySelector('#dados');
let erro = document.querySelector('#erro');

cep.addEventListener('blur', buscaCep);

function buscaCep(event) {
  // retorna ao estado inicial: erro escondido e dados vazios
  erro.classList.remove('ativo');
  dados.innerHTML = '';
  // faz a requisição ao web serivice
  fetch(`https://viacep.com.br/ws/${this.value}/json/`)
    .then(response => response.json())
    .then(json => {
      // se retornou erro mostar mensagem
      if (json.erro) {
        mostraErro('CEP Inválido');
      } else {
        // senão mostra os dados
        dados.innerHTML = `
            CEP: ${json.cep}
            Logradouro: ${json.logradouro}
            Complemento: ${json.complemento}
            Bairro: ${json.bairro}
            Localidade: ${json.localidade}
            UF: ${json.uf}
            Unidade: ${json.unidade}
            Cód. IBGE: ${json.ibge}
        `;
      }
    })
    .catch(response => {
      // Se ocorreu um erro na request mostra o erro
      mostraErro(response);
    })
}

// Apenas modifica o conteúdo do elemento e adiciona a classe que torna visível
function mostraErro(mensagem) {
  erro.innerHTML = mensagem;
  erro.classList.add('ativo');
}
#erro {
  display: none;
  color: red;
  border: 1px dashed red;
  margin: 10px;
  padding: 5px;
}

#erro.ativo {
  display: block;
}
<input id="cep">
<div id="erro"></div>
<pre id="dados"></pre>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.