Home > Software engineering >  How to access a specific html in python Flask?
How to access a specific html in python Flask?

Time:03-29

I am trying to make an RPG character-sheet using flask. In this project I have two buttons ( level and level- ) that add or decrease the level of the character when pressed on.

So I have my html file:

<div >
  <button type="button" name="level-">-</button>
  <p>{{ level }}</p>
  <button type="button" name="level "> </button>
</div>

and my flask file:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods=['POST', 'GET'])
def index():
    level = 0
    
    return render_template('index.html', level=level)

if __name__ == '__main__':
    app.run(debug=True)

How do I access the buttons such that I can increment or decrement the level variable in the python file?

CodePudding user response:

If you want it to have server-side actions, you will probably need to create a HTML form of it to make the browser send a POST request to your websites API. If you want it to have client-side actions, you will need to create a Javascript script so the browser executes code when a user presses the button.

CodePudding user response:

I suggest doing this with javascript instead since it's less resource-intensive than sending a request to the backend and passing the new level to the template.

<div >
    <button type="button" name="level-" onclick="changeLevel(-1)">-</button>
    <p id="level_number">{{ level }}</p>
    <button type="button" name="level " onclick="changeLevel(1)"> </button>
</div>
    
<script>
    function changeLevel(change) {
      var x = document.getElementById("level_number");
        if (parseInt(x.innerHTML)   change >=0){
            x.innerHTML =  parseInt(x.innerHTML)   change;
        }
    }
</script>

If you need the level in your backend, then you could use AJAX or use a hidden input in a form and read the value in the backend using request.form["level_number"]

<form >
    <button type="submit" name="level-" onclick="changeLevel(-1)">-</button>
    <p id="level_number">2</p>
    <input type="hidden" name="level_number" id="hidden_level_number" value="{{ level }}"/>
    <button type="submit" name="level " onclick="changeLevel(1)"> </button>
</form>
        
<script>
    function changeLevel(change) {
        var x = document.getElementById("level_number");
        var y = document.getElementById("hidden_level_number");
        if (parseInt(x.innerHTML)   change >=0){
            x.innerHTML =  parseInt(x.innerHTML)   change;
            y.value=x.innerHTML;
        }
    }
</script>

  • Related