In substrate node template we can see that blocks are producing and finalizing if no transaction happening so how I can make my node to only generate blocks when there are transactions happening.
There are two consensus (or "block authoring" --whichever you prefer to call them) algorithms that might be exactly what you need:
1- Manual seal: Where there is one author and it authors a block whenever you tell it via an RPC call.
2- Instant seal: Where there is one author and it attempts to author a block as soon as it sees a transaction in the pool, most often leading to one transaction per block
There is a substrate seminar where they build a substrate node that uses manual seal and instant seal consensus.